Use AI to write blog posts!

It’s no doubt that AI has really taken the world by storm recently, so let’s integrate it with our WordPress website and write some blog posts automatically!

The first function we will need to add is simply a wrapper for OpenAI’s API

function atom_call_openai( $prompt ) {
   $API_KEY = /* YOUR API KEY HERE */
   $url = 'https://api.openai.com/v1/completions';
   $data = array(
    'prompt' => $prompt,
    'model' => 'text-davinci-003', // consider making this dynamic as well
 	'max_tokens' => 2048,
	'temperature' => 0.5,
   );

   $response = wp_remote_post( $url, array(
    'method' => 'POST',
    'body' => json_encode( $data ),
	  'data_format' => 'body',
          'timeout' => 45, // I noticed that the default timeout was not long enough, this may vary for your server
	  'headers' => array(
		'Content-Type' => 'application/json; charset=utf-8',
		'Authorization' => 'Bearer ' . $API_KEY
	)
   ) );

   // Check if the API call was successful
   if ( is_wp_error( $response ) ) {
    return new WP_Error( 'api_error', $response, array( 'status' => 500 )  );
  } else {
    $body = json_decode( wp_remote_retrieve_body( $response ) );
    return $body;
  }
}

There is nothing really that fancy going on with the above code, we take in a $prompt string and send it to the OpenAI API, returning the response. Next up let’s call this function in a WordPress hook.

function grab_ai_content( $post_id ) {
    // If this is a revision, get real post ID.
    $parent_id = wp_is_post_revision( $post_id );

    if ( false !== $parent_id ) {
        $post_id = $parent_id;
    }

    // Get ACF field called 'ai_request'.
    $airequest = get_field( 'ai_request', $post_id);

    // Check if the 'ai_request' exists.
    if ( $airequest ) {
      // Call our openai wrapper
      $returndata = atom_call_openai ( $airequest );

      if ( $returndata ) {
	
        // unhook this function so it doesn't loop infinitely
        remove_action( 'save_post', 'grab_ai_content' );

        $postcontent = '<p><em>Note: The following blog post was written 100% by AI</em></p>';

	$postcontent = $postcontent . $returndata->choices[0]->text;

        // update the post, which calls save_post again.
        wp_update_post( array( 'ID' => $post_id, 'post_content' => $postcontent ) );

        update_field( 'ai_request', null,  $post_id);

        // re-hook this function.
        add_action( 'save_post', 'grab_ai_content' );
      }	
    }
}
add_action( 'save_post', 'grab_ai_content' );

The above function will run when a post is saved, if the post has value in the “AI Request” field it will call our OpenAI wrapper and save the response as the post content. Of course you could change this in so many ways, this is just a basic implementation. One more practical solution would be to use it to edit your existing post content or rewrite the content in a different tone. You can see an example of this in action in my previous post, where my original prompt was:

“Write a blog post for a new whiskey recipe, inspired by Cobourg, Ontario, Canada”

Have a look at the result below.

  • AI written blog post

    Note: The following blog post was written 100% by AI Whisky Cocktail Recipe Inspired by Cobourg, Ontario, Canada As the summer months approach and the days get warmer, it’s time to start thinking about refreshing drinks that can cool you down. If you’re looking for something a little more special than the usual lemonade or…

    Read More

Ultimately we are just at the beginning of the AI Era, what we create and how we use it will change quickly. Enjoy the ride!