Building a WP extension that auto-creates posts using AI API from form data

I’m trying to build a WordPress addon that takes form input and uses AI to write content

I want to make a plugin that grabs data from a contact form, sends it to an AI service, and shows the generated content to users. I’m new to WordPress development but managed to put together some code. The issue is when I hit the submit button, nothing happens and I see “text: null” in the browser console.

main-plugin.php

<?php
/*
Plugin Name: Content Creator AI
Description: Creates articles using GPT API
Version: 1.0
Author: developer
*/

define('GPT_API_TOKEN', 'your_api_token_here');
define('GPT_ENDPOINT', 'https://api.openai.com/v1/chat');

add_shortcode('content_generator_form', 'display_generator_form');
function display_generator_form() {
  ob_start();
  ?>
  <div class="content-generator-wrapper">
    <?php echo do_shortcode('[contact-form-7 id="5" title="Generator Form"]'); ?>
  </div>
  <?php
  return ob_get_clean();
}

add_action('rest_api_init', 'setup_content_endpoint');
function setup_content_endpoint() {
  register_rest_route('content-ai/v1', '/create-post', array(
    'methods' => 'POST',
    'callback' => 'handle_content_generation',
  ));
}

function handle_content_generation($request) {
  $data = $request->get_params();
  
  $subject = sanitize_text_field($data['post_subject']);
  $tone = sanitize_text_field($data['content_tone']);
  $summary = sanitize_textarea_field($data['brief_summary']);
  
  $user_prompt = "Subject: $subject\nTone: $tone\nSummary: $summary\nCreate article:";
  
  $payload = array(
    'prompt' => $user_prompt,
    'temperature' => 0.7,
    'max_tokens' => 400,
    'n' => 1,
  );
  
  $request_args = array(
    'headers' => array(
      'Content-Type' => 'application/json',
      'Authorization' => 'Bearer ' . GPT_API_TOKEN,
    ),
    'body' => json_encode($payload),
    'timeout' => 25,
  );
  
  $api_response = wp_remote_post(GPT_ENDPOINT . '/completions', $request_args);
  
  if (is_wp_error($api_response)) {
    return new WP_Error('request_failed', $api_response->get_error_message());
  } else {
    $response_body = wp_remote_retrieve_body($api_response);
    $parsed_data = json_decode($response_body, true);
    $generated_content = $parsed_data['choices'][0]['text'];
    return array('text' => $generated_content);
  }
}

add_action('wp_enqueue_scripts', 'load_generator_scripts');
function load_generator_scripts() {
  wp_enqueue_script('content-generator', plugins_url('/scripts/generator.js', __FILE__), array('jquery'));
  wp_localize_script('content-generator', 'generatorConfig', array(
    'endpoint' => rest_url('content-ai/v1/create-post'),
    'security' => wp_create_nonce('wp_rest'),
  ));
}
?>

generator.js

jQuery(function($) {
  $('#content-form').on('submit', function(e) {
    e.preventDefault();
    
    var formInfo = $(this).serialize();
    
    $.ajax({
      url: generatorConfig.endpoint,
      method: 'POST',
      data: formInfo,
      beforeSend: function(xhr) {
        xhr.setRequestHeader('X-WP-Nonce', generatorConfig.security);
      },
      success: function(data) {
        if (data.text) {
          $('#generated-content').html(data.text);
        } else {
          $('#generated-content').html('No content received');
        }
      },
      error: function(xhr) {
        $('#generated-content').html('Request failed: ' + xhr.responseText);
      }
    });
  });
});

Anyone know why I’m getting null responses from the API call?

quick debug tip - add some error logging to see whats actually happening. throw a error_log(print_r($api_response, true)); right after your wp_remote_post call to check if youre even getting a response. also ur form selector might be wrong - cf7 forms dont use id=“content-form” by default, they generate their own ids. check the actual html output

Had this exact problem a few months back when integrating with OpenAI. Your JavaScript is targeting a form ID that probably doesn’t exist - Contact Form 7 generates its own form classes and IDs dynamically. Instead of $('#content-form'), you need to target the actual CF7 form. Try using $('.wpcf7-form') or inspect your page to find the real form selector. Another thing I noticed is you’re missing the nonce verification in your REST endpoint callback function. Add wp_verify_nonce($request->get_header('X-WP-Nonce'), 'wp_rest') at the beginning of your handle_content_generation function. Without proper nonce verification, WordPress might be blocking your requests. Also make sure your Contact Form 7 field names match exactly what you’re looking for in the PHP - if your form has a field named ‘your-subject’ but you’re checking for ‘post_subject’, that would explain the null values you’re seeing.

The issue appears to be with form data not reaching your endpoint properly. When using Contact Form 7, the form fields need to be properly mapped to your REST API parameters. CF7 doesn’t automatically serialize form data the way standard HTML forms do. You’ll need to hook into CF7’s submission process using wpcf7_mail_sent action instead of relying on JavaScript form submission. I’ve built similar plugins and found that CF7 requires specific handling - the field names in your form need to match exactly what you’re expecting in $data['post_subject'] etc. Also worth checking if your REST route permissions are set correctly since you’re not specifying any permission callback, which might cause authentication issues. Try adding 'permission_callback' => '__return_true' to your register_rest_route array for testing purposes.

I ran into a similar issue when working with OpenAI’s API in a WordPress plugin last year. The problem is likely with your API endpoint URL and payload structure. You’re using the old completions endpoint format but calling the chat endpoint. The chat completions endpoint expects a different payload structure with a ‘messages’ array instead of a ‘prompt’ field. Try changing your payload to something like: $payload = array('model' => 'gpt-3.5-turbo', 'messages' => array(array('role' => 'user', 'content' => $user_prompt)), 'temperature' => 0.7, 'max_tokens' => 400); and make sure your GPT_ENDPOINT is set to ‘https://api.openai.com/v1/chat/completions’. Also double-check that your API token is valid and has the necessary permissions. The null response usually indicates the API call is failing silently.