Building a WordPress extension to auto-generate content using ChatGPT integration with form data

Need help with WordPress plugin development for AI content creation

I’m working on a WordPress extension that takes user input from a contact form and uses it to generate articles through ChatGPT API. The plugin should grab form data, send it to the AI service, and display the generated content back to the user.

I’m new to WordPress plugin development and I’ve put together some code but I’m running into issues. When users click the generate button, nothing appears and the browser console shows “content: null” from the API response.

Here’s what I have so far:

content-creator.php

/*
Plugin Name: Smart Content Creator
Description: Creates articles using AI technology
Version: 1.0
Author: developer123
*/

// API configuration
define('AI_SERVICE_KEY', 'your_api_key_here');
define('AI_SERVICE_ENDPOINT', 'https://api.openai.com/v1/engines');

// Create shortcode for form display
add_shortcode('smart_content_form', 'display_content_form');
function display_content_form() {
  error_log("Form shortcode loaded");
  ob_start();
  ?>
  <div class="content-creator-wrapper">
    <?php echo do_shortcode('[contact-form-7 id="15" title="Article Request"]'); ?>
  </div>
  <?php
  return ob_get_clean();
}

// Setup REST API endpoint
add_action('rest_api_init', 'setup_content_endpoint');
function setup_content_endpoint() {
  error_log("Setting up API endpoint");
  register_rest_route('content-creator/v1', '/create-article', array(
    'methods' => 'POST',
    'callback' => 'handle_content_creation',
  ));
}

// Process content generation request
function handle_content_creation($request) {
  error_log("Content creation started");
  $input = $request->get_params();

  // Extract form values
  $subject = sanitize_text_field($input['article_subject']);
  $tone = sanitize_text_field($input['content_tone']);
  $summary = sanitize_textarea_field($input['brief_summary']);

  error_log("Parameters: Subject: " . $subject . ", Tone: " . $tone . ", Summary: " . $summary);

  // Create AI prompt
  $ai_prompt = "Article subject: $subject\nContent tone: $tone\nBrief: $summary\nCreate article:";
  error_log("AI Prompt: " . $ai_prompt);

  // Configure API call
  $request_data = array(
    'prompt' => $ai_prompt,
    'temperature' => 0.7,
    'max_tokens' => 800,
    'n' => 1,
  );
  $http_args = array(
    'headers' => array(
      'Content-Type' => 'application/json',
      'Authorization' => 'Bearer ' . AI_SERVICE_KEY,
    ),
    'body' => json_encode($request_data),
    'timeout' => 45,
  );

  // Make API call
  error_log("Making API request...");
  $api_response = wp_remote_post(AI_SERVICE_ENDPOINT . '/text-davinci-003/completions', $http_args);
  error_log("API call completed");

  // Handle response
  if (is_wp_error($api_response)) {
    $error_msg = $api_response->get_error_message();
    error_log("API failed: " . $error_msg);
    return new WP_Error('request_failed', $error_msg, array('status' => 500));
  } else {
    $response_body = wp_remote_retrieve_body($api_response);
    $parsed_json = json_decode($response_body, true);
    $generated_content = $parsed_json['choices'][0]['text'];
    error_log("Generated content: " . $generated_content);
    return array('content' => $generated_content);
  }
}

content-creator.js

jQuery(document).ready(function($) {
  $('#create-content').on('submit', function(e) {
    e.preventDefault();
    console.log('Content creation form submitted');

    // Collect form information
    var requestData = $(this).serialize();
    console.log('Request data:', requestData);

    // Make AJAX call
    $.ajax({
      url: content_creator_settings.api_endpoint,
      method: 'POST',
      data: requestData,
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', content_creator_settings.security_nonce);
      },
      success: function(data) {
        console.log('Success response:', data);
        var generated_text = data.content;
        if (generated_text) {
          console.log('Content generated:', generated_text);
          $('#article-output').html(generated_text);
        } else {
          console.log('No content returned');
          $('#article-output').html('No content was generated');
        }
      },
      error: function(xhr, status, error) {
        console.log('Request failed:', xhr.responseText);
        $('#article-output').html('Request failed: ' + xhr.responseText);
      }
    });
  });
});

Check your error logs first - they’ll show exactly where it’s breaking. I had the same problem and it was nonce validation failing silently. Your AJAX call needs to match WordPress’s nonce format, don’t just throw it in a header. Also, that AI_SERVICE_KEY define probably isn’t pulling your actual API key unless you hardcoded it. Use wp_options or a config file instead.

Building a WordPress plugin for form data, API calls, and content display is way more complex than it needs to be. You’re juggling REST endpoints, nonces, Contact Form 7 integration, and API deprecation issues all at once.

I’ve done similar content generation workflows at work - skip the custom plugin entirely. Set up automation that watches form submissions, processes them through ChatGPT, and pushes content back to WordPress.

Here’s my approach: Connect Contact Form 7 to a webhook that triggers automation. It grabs form data, formats it for OpenAI’s chat completions API, gets the response, and creates a draft post or displays it wherever you need.

You’ll avoid PHP debugging, JavaScript coordination headaches, and WordPress API complexity. When OpenAI changes their API again, you just update one automation instead of rewriting plugin code.

I use Latenode for this exact workflow. It handles webhook receiving, AI processing, and WordPress posting without custom code. Takes 10 minutes to set up versus weeks debugging plugin issues.

I’ve built something similar and hit the same null content issue. Your problem’s probably the API endpoint URL. OpenAI changed their structure - you can’t use /engines/text-davinci-003/completions anymore. Switch to /chat/completions with the newer GPT models.

Also, your JavaScript looks for a form with ID create-content, but Contact Form 7 generates different field names and structure. Hook into CF7’s events instead - use wpcf7mailsent or wpcf7submit rather than a generic form handler.

I also ran into nonce verification issues. Make sure you’re actually enqueueing your JS file and using wp_localize_script() to pass the nonce and API endpoint to your script. If you skip proper enqueueing, your content_creator_settings object will be undefined.

Your JavaScript and PHP aren’t talking to each other properly - that’s why you’re getting null responses. Your JS sends serialized form data, but PHP expects specific names like article_subject, content_tone, and brief_summary. Contact Form 7 won’t automatically map these unless you set up the form fields right.

Your REST API route is missing permission callbacks too. WordPress blocks unauthenticated requests by default, so add 'permission_callback' => '__return_true' to your register_rest_route array. Or even better, add proper user verification.

That OpenAI API code is outdated - davinci-003 got deprecated. You need to switch to the chat completions endpoint with GPT-3.5 or GPT-4. The whole request format changed - it uses a messages array instead of the prompt parameter.

Double-check that your Contact Form 7 fields are named exactly what your PHP expects, or change how you extract parameters to match CF7’s naming.