Artificial intelligence (AI) can elevate your development workflow to the next level. The technology can perform complex and simple tasks – saving you time and increasing your earning power.

Nowhere is that more evident than in AI’s ability to write code. You tell your favorite tool what to do, and it generates the code. This is a boon to WordPress developers as you can create custom plugins with less effort. It’s like having an expert at your side.

That all sounds wonderful. But how does AI help developers in real-world scenarios? Is it capable of generating a decent solution without too much trouble? Let’s find out!

We’ll attempt to build a simple related posts plugin to give you a taste of what’s possible. We don’t expect it to compete with a commercial product. However, we hope to generate a functional piece of code; one that can be enhanced as needed.


best hosting for WordPress developers.

What Do We Want Our Plugin to Do?

AI is powerful – but it can’t read our minds just yet. Thus, we should think about what we want to build beforehand. A well-defined prompt will produce better results.

Like any development project, it’s better to start with the basics. With that in mind, let’s consider the core functions of a related posts plugin. It should:

  • Scan the current post’s metadata, including categories and tags;
  • Search the site’s database for other posts with similar metadata;
  • Display links to a specified number of related posts at the bottom of the current post;

The idea is to build a plugin that performs these tasks – and nothing else. Once that is established, you can add more bells and whistles.

Let’s Get To Work

It’s time to see how much effort it takes for AI to produce our plugin. We’ll use ChatGPT for this exercise, but you can use the tool you like best.

We’ll test our plugin on a local site with a selection of Speckyboy posts we’ve imported. The content spans several WordPress taxonomies (categories and tags). It should show us how well the plugin connects the dots (or doesn’t).

Step 1: Write a Prompt

Here’s our prompt to ChatGPT that covers the basics outlined above:

Create a WordPress plugin that displays posts related to the current one. It should do the following:

- Check the categories and tags assigned to the current post;
- Search the site's database for other posts with similar metadata;
- Display links to 4 related posts at the bottom of the current one;

Within a couple of minutes, ChatGPT generates a related posts plugin. Here’s what it tells us about the code:

Here's a WordPress plugin that displays related posts based on shared categories and tags. It retrieves up to four related posts and displays them at the bottom of the current post. The plugin uses `WP_Query` to fetch related posts efficiently.

This plugin fetches and displays related posts by:

1. Checking the current post's categories and tags.
2. Querying the database for other posts with matching categories or tags.
3. Displaying up to four related posts at the bottom of the content.

Step 2: Review the Code

Now, let’s do a quick review of the plugin’s code. That allows us to see what it does and spot any potential issues.

Note that we made a few adjustments to the plugin header to match the desired name and author info. In retrospect, we could have asked ChatGPT to add this. Thankfully, the changes are minimal.

Regardless, here’s our code. We’ll highlight a few items of interest below.

A Bit of Security: The first thing we’ll highlight is a line dedicated to security:

if (!defined('ABSPATH')) exit; // Exit if accessed directly

This code prevents someone from directly accessing the plugin file. It’s a bit of obfuscation that helps protect your website.

Query Our Blog Posts:

$args = [
 'post_type'      => 'post',
 'post_status'    => 'publish',
 'posts_per_page' => 4,
 'post__not_in'   => [$post_id],
 'orderby'        => 'rand',
 'tax_query'      => [
 'relation' => 'OR',
 ]
 ];

Here are the arguments for our WordPress post query. This snippet tells our plugin to look in the 'post' post type and choose four related posts. It uses the post_not_in argument to ensure the current post isn’t included in the query. The orderby argument is set to 'rand' to select related posts randomly.

Search Categories and Tags:

if (!empty($categories)) {
 $args['tax_query'][] = [
 'taxonomy' => 'category',
 'field'    => 'term_id',
 'terms'    => $categories,
 ];
 }
 
 if (!empty($tags)) {
 $args['tax_query'][] = [
 'taxonomy' => 'post_tag',
 'field'    => 'term_id',
 'terms'    => $tags,
 ];
 }

This snippet tells our plugin to look for posts using the same categories or tags as the current post.

Format the Related Posts List:

$output = '<div class="related-posts"><h3>Related Posts</h3><ul>';
 foreach ($related_posts as $related) {
 $output .= '<li><a target="_blank" href="' . get_permalink($related->ID) . '">' . esc_html(get_the_title($related->ID)) . '</a></li>';
 }
 $output .= '</ul></div>';

The plugin will output an unordered list of related posts. Each post’s link and title will be displayed. Notice the use of esc_html() to sanitize the title. That prevents any potentially dangerous code from executing.

Display at the Bottom of the Current Post:

 return $content . $output;
}
add_filter('the_content', 'rpd_display_related_posts');

Lastly, this snippet ensures the related post list displays at the bottom of the current post via the_content filter.

Step 3: Install and Activate the Plugin

Everything looks good so far. Next, we’ll copy the code generated by ChatGPT and place it in a file called speckyboy-related-posts.php. We’ll upload the file to the /wp-content/plugins/ folder on the test site. Finally, we’ll activate the plugin.

The plugin doesn’t produce any PHP errors, and our site didn’t break. We’ll consider that a victory!

We activated our related posts plugin with no issues.

Does Our Related Posts Plugin Work?

OK, we generated a plugin and installed it on our test site. It’s time to see if it works as intended.

To check, we’ll navigate to a blog post and hope a related posts list displays at the bottom:

A list of related posts displays at the bottom of each blog post.

Success! The plugin works well at first glance. There’s an unordered list of four related posts in the correct spot. Clicking each post reveals it shares a category and/or tag with the current post.

And the good news keeps on coming. Checking subsequent posts shows positive results. One or more taxonomies consistently match the current post. It may not be fancy, but it does the job!

We did notice an unintended side effect. Remember, our plugin chooses related posts randomly. Thus, refreshing the current post loads a fresh list at the bottom. That’s not necessarily a bad thing. It might benefit content-heavy sites, as it always gives readers something unique.

Finding the unexpected is part of the testing process. It’s an opportunity to refine and improve our plugin.

Taking Our Plugin to the Next Level

Our plugin works as expected and provides a solid foundation. But development doesn’t have to stop there. We can always add more features and advanced functionality.

We have a few ideas that could take this little related posts plugin to the next level:

Narrow the Scope of Related Posts

The current iteration looks for related posts that match a category and/or tag of the current one. That might be too broad for some use cases. Narrowing the scope of the search makes sense in this case.

We could limit matches to tags or even try to match keywords in the current post’s title. That could produce more relevant results. The downside? A more complicated search might mean a performance hit.

Improve Layout and Styling

The unordered list displayed by our base plugin is simple and accessible. There’s room for improvement, though.

For one, we could ask ChatGPT to create a card layout. That would look nice and neat on just about every site. In addition, we could add more post metadata such as featured images, publication dates, and excerpts.

A little CSS could also go a long way toward making the output look more professional. Hover effects would add some polish to the presentation.

Add a Settings Page

Our plugin has no settings. Adding a settings page could make it more flexible, though. A user might want to tweak several aspects of the plugin, including:

  • The number of related posts retrieved;
  • The post type(s) that should display related posts;
  • The criteria for related posts (taxonomies, keywords, etc.);
  • Posts or taxonomies to exclude;

It would be nice to have. However, plugin settings would also add a layer of complexity. Options must be saved to and retrieved from the site’s database. Plus, allowing user input comes with extra security responsibilities. That may not be desirable in every situation.

It’s a reminder to think about the consequences of each feature we add. Just because AI can do it, doesn’t mean we should ask!

AI Makes Building Plugins Easier Than Ever

It’s amazing to think about the speed at which AI produced our plugin. We went from a concept to a working prototype in about 10 minutes. It demonstrates the technology’s power and its level of improvement. Earlier versions of ChatGPT may not have been this efficient and accurate.

Granted, we weren’t trying to build the next WooCommerce. That’s still a bridge too far – especially when considering future maintenance and security needs.

Still, AI is adept at producing a simple plugin. Once you have that in hand, you can tweak it to your heart’s content. Adding features or making changes is a matter of writing a few prompts (or coding by hand, if you haven’t forgotten it yet).

Best of all, you can use these tools to your advantage. They’ll help you get projects done faster while expanding your development capabilities. It looks like the future is here!

Related Topics


Top

Similar Posts