Using ChatGPT To Write WordPress Plugins

As a follow on to the ChatGPT As A Coding Assistant article, this article delves into a specific type of coding – using ChatGPT to write WordPress plugins. Here I dig deeper into specific elements of utilizing ChatGPT to see how well it does in accelerating PHP coding, specifically as it relates to code to be run in WordPress. A big part of “WordPress coding” is writing plugins or themes. Having an intelligent assistant that understands the nuances of not only PHP but the open source WordPress core functions , filters, and hooks could speed up development significantly.

Here are my findings on the current state of ChatGPT 4 in performing this task.

My WordPress Plugin Development Experience

I’ve been writing WordPress plugins and themes for over a decade. I’ve written a successful plugin and built that into a SaaS platform, all based on the WordPress. You’ll find articles from years ago about using WordPress As An Application Framework. I’ve done several pro bono presentations at various technical conferences on the subject. I’ve also been a WordPress Core contributor, and author on various JetPack articles, and have written parts of the WordPress documentation over the years.

In other words, I have some expertise in the subject. Like most coders, I write both well-formed highly performant code as well as some less-than-optimal code depending on the day. I wanted to see how much ChatGPT could help me in writing WordPress plugins, not as a new developer looking for “lazy shortcuts” but as an experience developer looking for new methods, better ways of writing algorithms, or to just plain write those repetitive algorithms without having to pull it from my aging mid-50s brain.

How Well Did ChatGPT Write WordPress Plugins?

Turns out the results were underwhelming. Almost accurate, but not quite right. The code would run, but is adds extra unnecessary overhead and code complexity. In my opinion that is far worse than being just plain wrong. If you don’t know what you are looking at you’ll never catch the errors. Even worse, you’ll be learning bad techniques and pushing out yet more shitty code into the world. We already have plenty of that out there.

Here is a mid-level algorithm I was asking ChatGPT to assist with. My goal, to see if it would be faster to use ChatGPT to write this part of a WordPress plugin or not (it wasn’t):

Me: Write a PHP foreach loop that executes through a list of WordPress options names in an array named $options and fetches each option value. Assume the option value is a JSON object. Write an inner loop that loops through each key value pair and replaces a string contained in the variable $old_domain with a string contained in the variable $new_domain. Make sure the string replacement only replaces an exact word match using regex.

ChatGPT: To achieve the described functionality, you’ll need to loop through each option name in the $options array, fetch the option’s value (assuming it’s a JSON object), decode it to work with it as a PHP array or object, then perform the string replacement on each value using a regex that matches whole words only. Finally, you’ll re-encode the modified data back to JSON and update the option with the new value.

// Array of option names
$options = ['option1', 'option2', 'option3']; // Example option names

// Domain strings
$old_domain = 'example.com';
$new_domain = 'newexample.com';

// Define the regex pattern for whole word match
$pattern = '/\b' . preg_quote($old_domain, '/') . '\b/';

foreach ($options as $option_name) {
    // Fetch the option value (JSON)
    $json_value = get_option($option_name);
    
    // Decode JSON to PHP array for manipulation
    $decoded_value = json_decode($json_value, true); // decode as associative array

    // Check if decoding was successful
    if ($decoded_value) {
        // Iterate over each key-value pair in the array
        array_walk_recursive($decoded_value, function (&$item) use ($pattern, $new_domain) {
            // Check if the item is a string to avoid errors with non-string types
            if (is_string($item)) {
                // Perform regex replace for exact word match
                $item = preg_replace($pattern, $new_domain, $item);
            }
        });

        // Re-encode to JSON
        $updated_json_value = json_encode($decoded_value);

        // Update the option with the new value
        update_option($option_name, $updated_json_value);
    }
}

A good start, but there is some unnecessary overhead. I’ll let my next interaction with ChatGPT explain.

Me: That code is not correct or efficient for use in a WordPress function. Please rewrite that function using WordPress specific functions when possible.

ChatGPT: gave me the same exact code with slightly different prose beforehand saying it understood the task and would rewrite to keep WordPress specific functionality in mind.

Me: That is still not efficient or correct for use in a WordPress function. The WordPress get_option function automatically returns a decoded JSON object. Thus the $json_value variable is already decoded. The later json_decode call is redundant and may break the code. The WordPress update_option function automatically encodes complex arrays (objects) in JSON format. As such the subsequent json_encode($decoded_value) is not necessary. Please rewrite the function with that feedback in mind.

ChatGPT: Given the feedback and focusing on WordPress’s handling of JSON encoded option values, you’re correct that get_option will automatically decode JSON strings into PHP objects or arrays, and update_option will handle encoding PHP arrays or objects back into JSON strings. With this in mind, here’s a revised version of the function that omits unnecessary encoding and decoding:

// Array of option names
$options = ['option1', 'option2', 'option3'];

// Domain strings
$old_domain = 'example.com';
$new_domain = 'newexample.com';

// Define the regex pattern for whole word match
$pattern = '/\b' . preg_quote($old_domain, '/') . '\b/';

foreach ($options as $option_name) {
    // Fetch the option value, automatically decoded if it was stored as JSON
    $option_value = get_option($option_name);
    
    // Proceed only if the option value is an array or an object
    if (is_array($option_value) || is_object($option_value)) {
        // Recursively update the array or object
        array_walk_recursive($option_value, function (&$item) use ($pattern, $new_domain) {
            // Perform the replacement only on string values
            if (is_string($item)) {
                $item = preg_replace($pattern, $new_domain, $item);
            }
        });

        // Update the option with the modified value
        // WordPress will automatically encode it back into JSON if necessary
        update_option($option_name, $option_value);
    }
}

The latest iteration, pretty much spot on with what I would have written.

My Evaluation On Using ChatGPT To Write WordPress Plugins

In this particular case I was hoping to use ChatGPT as an assistant to save me time writing something I could write on my own. Overall I’d estimate this task would have taken me 15-20 minutes of my time at most, including test runs and validating the data stored in the wp_options table. Did ChatGPT do if faster? No. It did not provide an efficient answer until I did the typical back-and-forth thing to have it correct its errors. In the end I spent nearly an hour getting code in a format that I would deploy; In all honesty I already wrote that algorithm after the ChatGPT pass got it almost sort of right, then continue to push to find the boundaries of ChatGPT.

For new coders, this is dangerous. You’ll learn bad habits and not learn the inner workings of WordPress or efficient coding techniques. However for new coders this can also be super helpful. You will learn things like how to write a regex to test for word boundaries, or how to construct a decent foreach loop with decent variable names — well , maybe, I did heavily influence ChatGPT on both topics so maybe retrying this task with a new chat thread and see what it comes up with on its own may be in order.

That said, as with ANY INTERACTION with ChatGPT — assume it is telling half-truths. As the saying goes “trust but verify” , however with the current state of AI I’d refine that to “Assume bullshit, then verify and sift out the truth nuggets”.

Time to start digging into other coding tools like CoPilot to see how they fair.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.