How To Write A WordPress Plugin Tutorial - Step 2 - Action and Filter Plugin
The overview article provides some background and guidelines. If you haven't read that yet now might be a good time.
Perhaps the simplest plugin possible is one that uses a standard PHP library function as the plugin function. Remember the function must produce its output in the same way as the action to which it will be hooked. This can be seen in strrev() and the_title() as shown below:
<?php /* Plugin Name: Reverse The Title Plugin URI: https://brolgaswan.com/resources/wordpress/ Description: Reverse the title in posts, including excerpts. Version: 0.1 Author: Chris Crane Author URI: https://brolgaswan.com License: GPL2 */ add_action( 'the_title', 'strrev'); ?>
Try It Yourself - put the above code into a file of any name with the extension .php and put that into the plugins directory of your WordPress installation. In the admin plugins page there will now be a plugin Reverse The Title which you can activate and deactivate.
Notice how it changes the title everywhere it appears - menus, sidebars, as well as in the article itself. Let's refine that.
WordPress uses the programming concept of a simple loop to organise and display content. Once the loop has been entered WordPress will iterate to display all the posts given to it. This loop is used irrespective of the type of page, e.g. a home page showing excerpts of the top 5 most recent posts or a single page showing an article in full. Listing just the titles of the most recent posts (normally in a sidebar) is outside the loop whereas showing any part of the actual article, whether excerpt or entire article (in the main part of the page) is inside the loop. We can use a test for being inside the loop (or not) as a decision criterion within the plugin, viz:
<?php /* Plugin Name: Reverse The Title Plugin URI: https://brolgaswan.com/resources/wordpress/ Description: Reverse the title in posts, including excerpts. This applies only to the title within the actual post. Version: 0.2 Author: Chris Crane Author URI: https://brolgaswan.com License: GPL2 */ function rtt_cghc_strrev($input) { if(in_the_loop()) { $output = strrev($input); } else { $output = $input; } return $output; } add_action('the_title', 'rtt_cghc_strrev'); ?>
Try It Yourself - update your v0.1 code with the v0.2 code above and see the difference on your site. In this version the only place the title will be reversed is the main section of the page where articles and their excerpts are displayed.
Notes on the function rtt_cghc_strrev():
- The output is returned (not echoed) because this is what the original function the_title() does;
- Output is provided irrespective of whether or not the input is modified.
Exercise - see what happens if you don't output the unchanged version (comment out the line inside the else statement).