WordPress Plugin development by example – SF Generate Tags

By , last updated November 24, 2019

One of the plugins that we have developed for WordPress is a tag generator for WordPress posts and pages. The plugin scans the content of the post and names of the attached images and selects tags for the post filtering out no-tag words. In this post I’m going to explore the process of creating the plugin.

SF Generate Tags plugin consists of two parts: an algorithm for generating tags and an admin panel for post editing. All code is written in PHP. The plugin has extendable features like extra filtering algorithm for different languages.

Creating plugin

The process of creating plugins is simple with WordPress. Read more about it at official WordPress site. For simplest plugin you’ll need to create two files:
1. readme.txt
2. PHP file

Readme file

This file is mandatory and must be included in the plugin folder. This text file describes your plugin. All information seen at WordPress.org about your plugin is taken directly from this file. WordPress.org did a great job of telling developers how to write this file correctly. Take a look at it.

Main PHP file

In order for WordPress to see that this folder contains a plugin, it should have at least one PHP file with a standard WordPress plugin header. Here’s a very detailed description of that.

You don’t need to fill out all the fields, just the most important ones. Example from our SF Generate Tags plugin (sf-tags.php):

/**
 * Plugin Name: SF Generate Tags
 * Plugin URI: http://studiofreya.com/sf-generate-tags/
 * Description: This plugin autogenerates tags for your posts from attached images names and post text
 * Version: 1.0
 * Author: Studiofreya AS
 * Author URI: http://studiofreya.com
 * License: GPL3
 */

If your plugin is tiny with little logic, then all the code can be put in this one file. But usually some more logic is needed so it is advisable to put only a minimum there that will initialize the rest of the plugin.

For the purpose of SF Tags plugin, we need code for the admin panel and logic to generate tags.

Creating admin panel widget

A new PHP file is created for admin widget functionality: sf-tags-admin.php. Additional PHP files don’t need any standard headers. The only requirement is that it should be added to the plugin. In our main PHP file sf-tags.php I included it as follows:

function init_tags() {

	if ( is_admin() ) {
		require( 'sf-tags-admin.php' );
		new SFTags_Admin();
	}
}
add_action( 'plugins_loaded', 'init_tags' );

The code for the admin panel meta box is encapsulated in the SFTags_Admin class. This class has a constructor that initializes my meta_box:

class SFTags_Admin {
	/**
	 * Constructor
	 */
	public function __construct() {
		// Box for advanced tags
		add_action( 'add_meta_boxes', array(__CLASS__, 'add_meta_boxes'), 10, 1 );
	}
	
	public static function add_meta_boxes( $post_type ) {
		add_meta_box('sf-tags-settings', __('Autogenerate Tags - Settings', 'sf-tags'), array(__CLASS__, 'metabox'), $post_type, 'side', 'core' );
	}
}

In order to add a meta-box to the admin sidebar I used WordPress built-in function add_meta_box and gave it parameters to place it in the sidebar just after the tags widget.

Creating “Generate Tags” button

The plugin looks like a button “Generate Tags”. The user clicks it after the post is written and saved.

In the admin panel while editing the post we can see a “Tags” widget. It’s used for better SEO and to give readers most correct search results.

tag widget admin panel WordPress

Our plugin will post tags into the existing “Tags” widget window. So we place our new “Generate tags” button just under this widget.

plugin widget admin panel autogenerate tags

We need two settings in the plugin:

  • From images. In this case the tags will be taken from the names of all attached images. This option is good if you are providing many images with good descriptive names. Giving images good names not only good for tagging your posts, but also makes your images searchable in search engines and thus improves your SEO ratings.
  • From text. This option will take tags from the post text. It’s optional as maybe you don’t want your search results to be based on post text.

Originally, I intended to place the code in the <form> tag. But the strangest thing happened – my form-tag kept disappearing all the time. My original code:

// Careful !!! Broken code ahead !!!
<form method="post" action="sf-tags-generate.php">
    <input type="checkbox" name="fromImages" value="A" />From images<br />
	<input type="checkbox" name="formText" value="B" />From text<br />
	<input type="hidden" name="postId" value="<?php echo "$post->ID" ?>"/>
	<input type="submit" name="submit" id="submit" class="button button-primary" value="Generate Tags"  />
</form>

The output was not quite what I’d expected it to be (as you see a form-tag is gone):

form tag disappeared in wordpress plugin

The reason the form-tag disappeared was that there already was a mother-form tag in the page. It’s not allowed to nest forms so our nested form-tag was being ignored.

form post stuff in wordpress edit admin panel

So, what we need is to pass the data to the PHP function without a form. We can try to use javascript and something like “onclick” function. I’ve tried that and it didn’t work. The reason – WordPress strips those functions.

So we are going to choose the easiest way possible – javaScript library jQuery:

<div class="sf-generate-tags-form">
		<input type="checkbox" name="sf_from_images" value="sf_from_images" id="sf_from_images" checked="checked" />From Images
		<input type="checkbox" name="sf_from_text" value="sf_from_images" id="sf_from_text" checked="checked"/>From Text
		<input type="hidden" name="sf_post_id" id="sf_post_id" value="<?php global $post; echo "$post->ID"; ?>">
    	<a class="button" id="btnSubmit">Generate Tags</a>
	</div>

We make two checkboxes, one hidden field with post-id and a submit button. Out script will then pick up the input and send it all to sf-generate-tags function that has actually tags filtering logic.

<script type="text/javascript">
    jQuery(document).ready(function()
	{
		jQuery('#btnSubmit').click(function ()
		{
			var sf_post_id = jQuery('#sf_post_id').val();
			var sf_from_images = jQuery('#sf_from_images').is(':checked')? 1:0;
			var sf_from_text = jQuery('#sf_from_text').is(':checked')? 1:0;
			
			jQuery.ajax({
				type: "POST",
				url: ajaxurl,
				
				data: {
					action : 'sf_generate_tags', 
					post_id: sf_post_id,
					from_images : sf_from_images,
					from_text : sf_from_text
				}
				}).done(function( msg ) {
					jQuery("#new-tag-post_tag").val(msg);
					jQuery(".ajaxtag input.button").trigger('click');   
				 });
		});
	});
</script>

Some explanation of jQuery code:

  • To get the information on whether the checkbox is checked or not without submitting a form we used this special annotation “checked”:
    jQuery('#sf_from_images').is(':checked')? 1:0;
    
  • The retrieve a dynamic post id we used function val():
    jQuery('#sf_post_id').val();
    
  • To post the resulting tags (msg) into “Tags” widget we put them into tags field:
    jQuery("#new-tag-post_tag").val(msg);
    
  • Finally, we triggered automatic click of “Tags” input button with jQuery as well:
    jQuery(".ajaxtag input.button").trigger('click');   
    

The function with the algorithm will pick up the data and process it. It is achieved by catching POST requests in real time:

function sf_generate_tags() {
	$postId = (int)$_POST['post_id'];
		
	$tagsFromImages = (int)$_POST['from_images'];
	if($tagsFromImages == 1)
	{
		//some code
	}
	
	$tagsFromText = (int)$_POST['from_text'];
	if($tagsFromText == 1)
	{
		//some other code
	}
}

Next step is to write the logic for getting tags from images and text.

Download code of the SF Generate Tags plugin at WordPress.

Senior Software Engineer developing all kinds of stuff.