Anatomy Of A WordPress Plugin: Adding Admin Submenus For Options Pages

WordPressI have not yet written a plugin for WordPress that is complex enough to require the settings to be broken down over multiple pages in the Admin area, but this is something that is possible to do fairly easily.

In the last post we covered adding a link on the menu using the add_options_page function.

This function works for a single options page, but this function doesn’t work for submenus.

Instead we need to use add_menu_page to add the top level menu and add_submenu_page.

As with add_options_page, these functions are called using the add_action function with the admin_menu hook to call a custom function.

The code below shows the two functions being called for a mocked up example:

add_action("admin_menu", "azc_create_menus");

function azc_create_menus() {
    add_menu_page( "azurecurve Menu"
			, "azurecurve Menu"
			, 0
			, "azurecurve-menu-slug"
			, "azurecurveMenuPageFunction"
			, plugins_url( '/images/favicon.ico', __FILE__ ) );
    
	add_submenu_page( "azurecurve-menu-slug"
			, "azurecurve Submenu"
			, "azurecurve Submenu"
			, 0
			, "azurecurve-submenu-slug"
			, "azurecurveSubmenuPageFunction" );
}

Continue reading

Anatomy Of A WordPress Plugin: Adding Admin Menu For Options Page

WordPressAll but the most simple of WordPress plugins will require an options page in the Admin area which will need to be made accessible to the admin users. The main way this would be done is to add an entry to the admin menu.

This is done using the add_action function with the admin_menu hook to call a custom function.

This custom function then uses the add_options_page function to add the options page to the Settings menu.

The code below is from my RSS Suffix plugin where a menu option called azurecurve RSS Suffix is calling a function called azc_rss_config_page:

add_action( 'admin_menu', 'azc_rss_settings_menu' );

function azc_rss_settings_menu() {
	add_options_page( 'azurecurve RSS Suffix'
						,'azurecurve RSS Suffix'
						,'manage_options'
						,'azurecurve-rss-suffix'
						, 'azc_rss_config_page' );
}

Continue reading

Anatomy Of A WordPress Plugin: Shortcode Extract Of Parameters

WordPressIn my last post I discussed adding a shortcode to the plugin and covered how to extract the parameters passed into the function from the shortcode.

There is one variation to this example which it is probably worth mentioning. In the last post I showed that the width parameter could be extracted using the following code:

extract(shortcode_atts(array(
		'width' => '75%'
	), $atts));

This extracts the parameter so it can be used as $width; if multiple parameters were extracted then they would all be used in a similar way.

However, you can also extract the parameters into an array for use:

$parameters = shortcode_atts(array(
		'width' => '75%'
	), $atts);

This would make the width parameter available by referencing the array:

return $parameters['width']};

I typically use the former approach, but using the latter would make it more readily apparent when the variables being used had been passed in from the shortcode or set within the function.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

Anatomy Of A WordPress Plugin: Adding A Shortcode

WordPressAdditional functionality can be added to posts and pages through the use of shortcodes. Up to now I have created and published six plugins of which two thirds use a shortcode to add easy-to-use additional functionality.

For example the Series Index plugin uses a [series-index] shortcode to display the series index for the posts. To use a shortcode, it first needs to be added and then the function itself which does the action specified by the shortcode is created.

A shortcode is added using the add_shortcode() function:

add_shortcode( $tag, $function );

The structure of the function call is:

  • $tag – the shortcode tag is searched for in the post or page and will be replaced with the return of the $function.
  • $function – is the hook called when the tag is found in the post or page.

In the Series Index plugin, the add_shortcode() call looks like this:

add_shortcode( 'series-index', 'azc_display_series_index' );

The tag series-index causes the plugin to look for [series-index] in a post and page and then call the function azc_display_series_index to perform the required action.

Which segues us nicely into the second part of required code which is the function which executes the shortcode. At the simplest level the function needs the following:

function shortcode_function( $atts ){
	return "shortcode output";
}

$atts are the attributes passed in via the shortcode with the return line passing back the content which will replace the shortcode.

The Series Index plugin was created to take a number of parameters. This would be done by expanding the [series-index] shortcode to include them. For example, one of the parameters is the width; if we wanted the series index to be 80% of the width of the containing div, this would be added by adding width=’80%’ to the shortcode:

[series-index width='80%']

The atributes can be extracted from the $atts using the following code:

extract(shortcode_atts(array(
		'width' => '75%'
	), $atts));

This code extracts the $width parameter from the $atts and also sets a default of 75% if the width parameter is not supplied.

After the parameters have been extracted they can be used in the function to generate any output required. The Series Index function is a bit longer and more complex than I want to post here. So instead below is a section of the shortcodes function with several parameters being passed in:

function azc_display_series_index($atts, $content = null) {
	extract(shortcode_atts(array(
		'title' => "",
		'replace' => "",
		'width' => '75%,
		'toggle' => 1,
		'heading' => ""
	), $atts));
	
	{code excised for brevity}
	
	return $output;
}

The code which uses the parameters and sets the output has been excised for purposes of brevity.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

Anatomy Of A WordPress Plugin: Loading CSS & JavaScript Together

WordPressIn the last couple of posts in this series I’ve taken a look at using wp_enqueue_scripts to load the CSS and JavaScript files.

In those examples, the CSS and JavaScript were loaded via different functions. However, we could use add_action to call one function to load both the CSS and JavaScript.

If I were to amend the Floating Featured Image plugin to load the CSS and JavaScript in one function it would look like the following:

add_action('wp_enqueue_scripts', 'azc_ffi_load_css_and_javascript');

function azc_ffi_load_css_and_javascript(){
	wp_enqueue_script( 'azurecurve-series-index', plugins_url('jquery.js', __FILE__), array('jquery') );
	wp_enqueue_style( 'azurecurve-floating-featured-image', plugins_url( 'style.css', __FILE__ ) );
}

We use the add_action to call the azc_ffi_load_css_and_javascript function which now contains both wp_enqueue_script and wp_enqueue_style calls.

This isn’t necessary, as we could continue using separate add_action calls, but it does reduce the number of calls to wp_enqueue_scripts and the number lines of code required without adding any real complexity.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

Anatomy Of A WordPress Plugin: Loading The JavaScript

WordPressAdditional functionality can be added to a WordPress using JavaScript. For example, the Series Index uses JavaScript to allow the index to be shown or hidden when the user clicks a toggle link. The JavaScript will be stored in a separate file which, when I use it, I usually call jquery.js and is placed in the plugin folder alongside the main plugin file.

To make use of the JavaScript, the file then needs to be loaded within the plugin. When working with procedural code, the following snippet of code from my Series Index plugin shows how the file can be loaded:

add_action('wp_enqueue_scripts', 'azc_si_load_jquery');

function azc_si_load_jquery(){
	wp_enqueue_script( 'azurecurve-series-index', plugins_url('jquery.js', __FILE__), array('jquery'), '3.9.1');
}

The add_action hook can be used to call a function which then calls wp_enqueue_script; this is the “safe” way of loading a script file for a WordPress plugin.

The structure of the call is:

  • handle – the first parameter is the name of the script and is mandatory.
  • source – the location of the script file and is mandatory; this should never be hard-coded as it cannot be guaranteed to be the same on every site. Using the plugins_url function the path of the current file can be automatically retrieved

    The first parameter to plugins_url is the file we want, and __FILE__ will be used to determine the folder location of the plugin file; the returned data will be the path concatenated with the filename.

  • dependencies – an array containing all of the files which must be loaded before the one being loaded here.
  • version – the script version number; used to ensure the correct script is passed to the client. This parameter is optional and if not supplied will be defaulted to the WordPress version.
  • in footer – this optional parameter controls where the script is loaded. If not supplied, the scripts are placed in the element of the HTML document. If set to true, the script is placed before the end tag; this requires the theme to have the wp_footer() template tag in the appropriate place.

By using wp_enqueue_style, the script is loaded at the right time alongside the other scripts; at the start of the post I said this was the “best” way of including scripts, but it on reflection I should have stated that this is the “correct” way of including scripts into a plugin.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

Anatomy Of A WordPress Plugin: Loading The CSS

WordPressThe majority of the plugins I have created have created have an output visible to the user. For example, the Posts Archive can be used in a widget (see the side menu) or on a page. And to display the output to the best advantage it needs to be formatted; while this can be done using inline styles it is better done using an external stylesheet (or CSS file).

To use an external stylesheet, create the .css file, which I typically call style.css, in the plugin folder next to the main php file (you can put it in a sub-folder should you wish).

This file then needs to be loaded within the plugin. When working with procedural code, the following snippet of code from my Floating Featured Image plugin shows how the file can be loaded:


add_action('wp_enqueue_scripts', 'azc_ffi_load_css');

function azc_ffi_load_css(){
	wp_enqueue_style( 'azurecurve-floating-featured-image', plugins_url( 'style.css', __FILE__ ), '', '1.0.0' );
}

The add_action hook can be used to call a function which then calls wp_enqueue_style; this is the “safe” way of loading a style sheet for a WordPress plugin.

The structure of the call is:

  • handle – the first parameter is the name of the style and is mandatory.
  • source – the location of the stylesheet and is mandatory; this should never be hard-coded as it cannot be guaranteed to be the same on every site. Using the plugins_url function the path of the current file can be automatically retrieved

    The first parameter to plugins_url is the file we want, and __FILE__ will be used to determine the folder location of the plugin file; the returned data will be the path concatenated with the filename.

  • dependencies – an array containing all of the files which must be loaded before the one being loaded here.
  • version – the style sheet version number; used to ensure the correct stylesheet is passed to the client
  • media – optional string specifying the media for which this stylesheet has been defined, such as ‘screen’, ‘handheld’ or ‘print’. See this list for the full range of valid CSS-media-types. If not otherwise set will default to ‘all’

By using wp_enqueue_style, the stylesheet is loaded at the right time alongside the other stylesheets.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

Anatomy Of A WordPress Plugin: Coding Paradigms

WordPressHaving covered the basics of a WordPress plugin from the php tags to the file header, I thought a quick discussion of the code types in which WordPress plugins can be written and which I have used.

There are two code types that can be used:

  • Procedural Programming
  • Object Oriented Programming

There has been many a flame war fought over which is better and which is worse, but in all honesty I believe that both can have their place and there is no one true way of coding.

I was going to cover the differences between the two types, but when I was researching for good definitions I came across an article by Tom McFarlin linking to articles he and Stephen Harris wrote on the coding paradigms which can be used with WordPress plugins.

I am not old, but my programming career (short as it was and now a few years in the past after I moved into being a consultant) tended to be with older languages such as Databasic and Visual Basic; I also self-taught myself Lua and later PHP.

In all of the programming/scripting languages I have worked with the code has been procedural; I’m not saying all of these languages are only procedural, just that all of the code I worked with was. As such I am far happier in a procedural world and so I have used this for writing my plugins.

I do intend to delve into object oriented at some point, and probably rewrite the plguins as I do, but the plugins I have created I needed to get done fairly quickly as I was using cobbled together code stored in a theme functions file; the number of WordPress sites I run has risen quite quicky and I needed an easy way to distribute the code between them (this also explains why I make all of my plugins multisite compatible). Most of the examples available online for WordPress plugins is procedural which made my choice easier.

The exception to this is widgets; WordPress widgets can only be written using object oriented programming so I will be covering some of this coding paradigm as the series progresses.

Click to show/hide the Anatomy Of A WordPress Plugin Series Index

Anatomy Of A WordPress Plugin: The Basics

WordPressThroughout this Anatomy Of A WordPress series I am going to be running through a number of the functions I use a lot and other items required when developing plugins. But, for the first post, it is probably best to start at the very beginning.

When creating a WordPress plugin, the first thing to do is to create the folder in which the files are to be stored. When doing so it is best to pick a name which is going to be unique; I am also typically giving them a name which will group all of my plugins together.

All of the plugins I have created so far have azurecurve at the start of the name. e.g.

azurecurve-rss-suffix

Within the file create a php file of the same name with the php suffix:

azurecurve-rss-suffix.php

Open the file and enter the php tags, between which all php code will be entered, at the top and bottom:

<?php
?>

Continue reading

Anatomy Of A WordPress Plugin: Series Index

WordPressHaving recently taken up writing plugins for WordPress I am currently on quite a step learning curve; these posts will serve as reminders to myself on what the different parts of a WordPress plugin arehow they hang together.

If anyone spots something which could be better, or is flat out wrong, please leave a comment explaining why and how to do better.

This post is the series index, displayed below, which will expand to show new posts as they are published:

Anatomy Of A WordPress Plugin
The Basics
Coding Paradigms
Loading The CSS
Loading The JavaScript
Loading CSS & JavaScript Together
Adding A Shortcode
Shortcode Extract Of Parameters
Adding Admin Menu For Options Page
Adding Admin Submenus For Options Pages