How to build a WordPress Plugin to reply comment with ChatGPT

ChatGPT has been a hot topic recently due to its impressive capabilities in natural language processing and generation. Its applications in chatbots, customer service, and content creation have made it a valuable tool for businesses and developers looking to enhance user experiences and improve engagement.

Then the idea come into my mind, let’s integrate WordPress with ChatGPT! Let it help us reply comments. This can be particularly useful and time-saving if you receive a high volume of comments on your website and struggle to keep up with replying to each one individually.


WordPress Plugin Reply with ChatGPT demo


GitHub repository

You can download the WordPress Plugin code of the above demo in the link below:


Step by step guide to build the WordPress Plugin

ChatGPT is a language model developed by OpenAI, an artificial intelligence research laboratory that specializes in the creation and advancement of AI technologies. OpenAI offers an API that enables developers to access the powerful language models developed by the organization, including GPT-3, GPT-2, and other models. These can be used to generate text, translate languages, analyze sentiment, and more. Developers can integrate the API into their applications or websites, allowing users to interact with AI-generated content in a seamless and natural way. I am going to show you step by step how did I build a WordPress Plugin to “Reply with ChatGPT”.

# Step 1 : Create the plugin folder

In the host of WordPress website, navigate to /wp-content/plugins folder. Create a new folder “chatgpt-reply”

And then add below files into the plugin folder, we will explain each file one by one in this article

# Step 2 : Add Plugin info file

chatgpt-reply.php is the plugin description file with the Plugin Name, Description, Version, Author.

<?php
/*
Plugin Name: ChatGPT Reply
Description: Adds a "Reply with ChatGPT" opion to the wp-admin comment page. call OpenAI API to auto generate text to reply 
Version: 1.0
Author: Benson Ruan
*/

define( 'CHATGPT_REPLY__PLUGIN_DIR', plugin_dir_path( __FILE__ ) );

require_once( CHATGPT_REPLY__PLUGIN_DIR . 'chatgpt-reply-js.php' );
require_once( CHATGPT_REPLY__PLUGIN_DIR . 'chatgpt-reply-option.php' );
require_once( CHATGPT_REPLY__PLUGIN_DIR . 'chatgpt-reply-settings.php' );

# Step 3 : Add Reply with ChatGPT option

chatgpt-reply-option.php contains below code, it add the “Reply with ChatGPT” option for each comment.

<?php
// Add button to comment row actions
function add_chatgpt_button_to_comment_row_actions($actions, $comment) {
    $actions['chatgpt_reply'] = '<a href="#" class="openai-reply">Reply with ChatGPT</a>';
    return $actions;
}
add_filter('comment_row_actions', 'add_chatgpt_button_to_comment_row_actions', 10, 2);

# Step 4 : Add Settings Page

chatgpt-reply-settings.php is the file for the admin settings of this plugin

Put below code in the file, this is to add a “ChatGPT Settings” into the admin menu

<?php
// Define plugin settings page
function chatgpt_reply_settings() {
    add_menu_page(
        'Reply with ChatGPT Settings', 
        'ChatGPT Settings', 
        'manage_options', 
        'openai-comment-reply-settings', 
        'openai_comment_reply_settings_page', 
        'dashicons-format-chat' 
    );
}
add_action('admin_menu', 'chatgpt_reply_settings');

And then add a function to render the HTML of the settings, include a password input for the OpenAI API Key

function openai_comment_reply_settings_page() {
  $openai_api_key = get_option( 'openai_api_key' );
  ?>
  <div class="wrap">
    <h1>Reply with ChatGPT Settings</h1>
    <form method="post" action="options.php">
      <?php settings_fields( 'openai_settings' ); ?>
      <?php do_settings_sections( 'openai_settings' ); ?>
      <table class="form-table">
        <tr valign="top">
          <th scope="row">OpenAI API Key</th>
          <td>
		  <input type="password" required name="openai_api_key" class="regular-text" value="<?php echo esc_attr( $openai_api_key ); ?>" /></td>
        </tr>
      </table>
      <?php submit_button(); ?>
    </form>
  </div>
  <?php
}

At the end also need to register the setting

function openai_settings_init() {
  register_setting( 'openai_settings', 'openai_api_key' );
}
add_action( 'admin_init', 'openai_settings_init' );

# Step 5 : Add Javascript to call OpenAI ChatGPT API

chatgpt-reply-js.php is for the javascript function to call OpenAI’s API, pass the comment text as prompt, and use the AI generated response as the reply text of the comment.

<?php
// Add JavaScript code to handle ChatGPT reply
function add_chatgpt_js_to_comment_page() {
	$openai_api_key = get_option( 'openai_api_key' );
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Add click handler to "Reply with ChatGPT" button
        $('.openai-reply').click(function() {
			var commentId = $(this).closest('tr').attr('id').replace('comment-', '');
			$('#comment-' + commentId + ' .row-actions .reply button').click();
			openai_reply(commentId);
            return false;
        });
		
		function openai_reply(comment_id) {			
			rowData = $('#inline-'+comment_id);
			comment_text = $('textarea.comment', rowData).val();
			editRow = $('#replyrow');
			$( '#replysubmit .spinner' ).addClass( 'is-active' );
			apiKey = "<?php echo esc_attr( $openai_api_key ); ?>";			
			$.ajax({
				type: "POST",
				url: "https://api.openai.com/v1/completions",
				headers: {
				  "Content-Type": "application/json",
				  "Authorization": "Bearer " + apiKey
				},
				data: JSON.stringify({
				  "model": "text-davinci-003",
				  "prompt": 'Reply to comment: ' + comment_text,
				  "max_tokens": 1024,
				  "temperature": 0.5
				}),
				success: function(response) {
				  var choices = response.choices;
				  if( choices.length > 0) {
					var choice = choices[0];
					var reply_text = choice.text;
					$('#replycontent', editRow).val( reply_text );
					$( '#replysubmit .spinner' ).removeClass( 'is-active' );
				  }
				}
			});
		}
    });

    
    </script>
    <?php
}
add_action('admin_footer-edit-comments.php', 'add_chatgpt_js_to_comment_page');

To explain the above code further, it is doing things below

  • Get the comment text that it is replying
  • Use Ajax to call OpenAI API, pass the comment text as “prompt” parameter
  • Once API response return, extract AI generated response under choice.text
  • Place the response text into the Reply input textbox

# Step 6 : Create an OpenAI API Key

  • Go to the https://openai.com/product
  • Click on the “Get started” button.
  • Create an account or just Continue with your Google or Microsoft Account
  • Once your registration is complete, you will receive an email with instructions on how to activate your account.
  • Once your account is activated, log in to the OpenAI API dashboard.
  • Click on the “API Keys” tab and then click the “Create new secret key” button.
  • Copy the API key and save it to the “ChatGPT Settings” in step 4

Once you save the OpenAI API Key into the ChatGPT Settings, you can start using the “Reply with ChatGPT” function when reply comments, it is super convenient and time-saving, just let AI help you to do the job.


WodPress Plugin

I am very existing to announce that “AI Reply” is now available as a official WordPress plugin


OpenAI ChatGPT API details explain

For those that want to dig into OpenAI’s API, I had listed the details below

API url : https://api.openai.com/v1/completions

Authorization: Bearer YOUR_API_KEY

Request Object Properties

  • model – This parameter allows you to specify which language model you want the API to use to generate text
  • prompt – This parameter is required and contains the text prompt or context that you want the API to generate text based on.
  • max_tokens – This parameter controls the maximum length of the generated text, in terms of the number of tokens (words, phrases, etc.). You can set a specific number or use the default value of 2048.
  • temperature – This parameter controls the “creativity” of the generated text. A higher temperature value will result in more unpredictable and creative responses, while a lower temperature will result in more predictable and “safe” responses.

Response Object Properties

After you make a completion request to the OpenAI API, the API will return a JSON response that contains several properties that provide information about the generated text. Here are some of the most important properties in the response:

  • id – This is a unique identifier for the completion request. You can use this ID to retrieve the results of the request later.
  • model – This property indicates which language model was used to generate the text.
  • object – This property contains the generated text itself, as well as some additional metadata about the response.
  • created – This property indicates when the completion request was created.
  • choices – This property contains an array of possible text completions, along with their scores and other metadata.

Each element in the choices array includes the following properties:

  • text – The generated text completion.
  • index – The index of the generated text completion in the list of possible completions.
  • logprobs – The log-probabilities assigned to each token in the generated text.
  • finish_reason – A string indicating the reason why the text generation process was terminated.

Conclusion

The advancements made by OpenAI and ChatGPT are truly impressive and groundbreaking. the advancements they made represent a major leap forward in the field of natural language processing, and have the potential to revolutionize the way we interact with computers and technology in general. As these technologies continue to evolve, we can expect to see even more exciting applications and use cases emerge in the years to come.

By leveraging the power of advanced language models, you can generate dynamic and engaging responses that improve user engagement and satisfaction. With this step-by-step guide, you can easily implement this feature on your own website and start enjoying the benefits of ChatGPT today. So why wait? Start exploring the possibilities of OpenAI API and ChatGPT, and take your website to the next level!

Thank you for reading. If you like this article, please share on Facebook or Twitter. Let me know in the comment if you have any questions. Follow me on Medium, GitHub and Linkedin. Support me on Ko-fi.

6 Comments

  • Lauren Rodriguez on Apr 12, 2023, Reply

    I have read your blog on Which are the ways to use OpenAI on wordpress websites.It was very interesting and helpful but I can add some extra points in your article. Here some extra points:
    1.Generate Titles and Meta Descriptions with AIOSEO.
    2.Generate Ad Copy and Product Descriptions.
    3.Generate Blog Post Ideas.
    4.Perform Sentiment Analysis.
    5.Automate Customer Support with Intelligent Sentiment Analysis.
    These are some extra points to add to your article. Readers if you are confused about your web and App development , you can get a free consultation at Alakmalak technologies.Visit our site for more information.

  • Nagaraj on Jun 5, 2023, Reply

    Thanks for sharing useful information with us. It really helpful to me. thanks for sharing with us.

    • benson_ruan on Jun 11, 2023, Reply

      Thank you for taking the time to leave a comment and for your kind words! We are glad to hear that our content was helpful to you. Please feel free to reach out to us if you have any questions or suggestions for future articles.
      BTW, the WP Plugin in this article is now available for download on https://wordpress.org/plugins/ai-reply/

  • Emmanuel Imohi on Jul 14, 2023, Reply

    Sincerely, this alone has lured me so much to pick much interest into AI and ChatGPT integration with my small app. God bless you more

    • benson_ruan on Jul 15, 2023, Reply

      Thank you for your kind words! We’re delighted to hear that our content has sparked your interest in AI and ChatGPT integration. It’s an exciting field with endless possibilities. If you have any questions or need further guidance on implementing ChatGPT into your app, feel free to reach out. Best of luck with your project, and may you have continued success!

  • GPTNederlands on Sep 9, 2023, Reply

    The given statement provides an introduction to ChatGPT, OpenAI, and the API offered by OpenAI. It also mentions the capabilities of language models like GPT-3 and GPT-2, and how developers can integrate the API into their applications or websites. The statement further highlights the intention to demonstrate the process of building a WordPress Plugin to incorporate ChatGPT’s functionality.

    Overall, the statement provides a clear overview of the subject matter and sets the stage for explaining the process of creating a WordPress Plugin using ChatGPT. However, since the actual step-by-step demonstration is not included in the provided text, it is difficult to provide specific feedback on that aspect. Including the step-by-step guide would allow for a more comprehensive understanding and evaluation of the mentioned process.

    Additionally, it would be beneficial to include more details about the potential use cases and benefits of integrating ChatGPT into a WordPress Plugin. This would help readers better grasp the significance and value of such integration.

Leave a Reply