Chris Farrell Membership
Camtasia Studio
Snagit
This site uses cookies. By continuing to browse the site, you are agreeing to our use of cookies. Find out more.

131 Text to Hyperlink Filter Example (How-to Video)

 Posted by  Add comments
 

131 Text to Hyperlink Filter Example (Video)

Part of the “How to Write a WordPress Plugin” series

This Lesson – Overview

In this lesson we’ll continue the hooks, filters and actions topic with a demonstration filter. This continues the previous lessons where we introduced plugins, built a basic working plugin template file structure and created a plugin class for our plugin.

The task for this lesson is to search all your posts and convert specified keywords to hyperlinks. How long do you think this would take you? If you have more than just a few pages, quite a long time I would imagine. The good news, this is an ideal task for a filter. The even better news, the method we’ll employ changes the text as it is displayed (on-the-fly) so the underlying data is not modified.

So, in this demonstration we will write a text to hyperlink filter which will search all posts for the stipulated keywords and convert those keywords to hyperlinks.

i.e.: Convert keyword: WordPress (not case sensitive)

from:
… the WordPress site is an ideal place to find …
to:
… the WORDPRESS site is an ideal place to find …

Contents

Text to Hyperlink Filter Example

In our previous code we left placeholders where our plugins actions and filters code could be inserted.

// TODO: Enter Plugin Actions and Filters here
// TODO: Enter Action and Filter Methods here

So, using these placeholders, lets jump straight in and create a simple WordPress filter to demonstrate how easily plugins can be written when using our plugin class.

Hyperlink Filter Exercise

In this exercise we’ll change the word, “WordPress” into a capitalised hyperlink in all posts. To do this, the first thing we’ll need is a function which will actually do the work. We’ll call this function pk_text_to_hyperlink().

// TODO: Enter Action and Filter Methods here

// Change text to hyperlink
function pk_text_to_hyperlink( $content )
{
   $search ="WordPress";
   $replace ="<a title='Permalink to WordPress' href='http://wordpress.org/'>WORDPRESS</a>";
   $content = str_ireplace($search, $replace, $content);
   return $content;
 } // End function pk_text_to_hyperlink

This function will perform a case insensitive search for every occurrence of the keyword, “WordPress”. When found the keyword will be converted to a hyperlink and capitalised. The capitalisation is just to make the change very obvious on the screen. In reality you probably wouldn’t change the case.

  • This function could easily be expanded into a very useful plugin by using an array of keywords and hyperlinks. The addition of an admin panel and database would make it a very powerful application. But that’s an exercise for another lesson.

Now that we have our function to do the work, WordPress needs to be hooked into our code. As we are going to filter post content, we simply use the add_filter function.

// TODO: Enter Plugin Actions and Filters here
// Change text to hyperlink
add_filter('the_content', array(&$this,'pk_text_to_hyperlink'),1);

The first parameter we need is the WordPress hook or $tag. As we are modifying the content of the post, the hook we need is, the_content hook.

The second parameter we need is the name of the function the filter will call, that’s the name of our function, pk_text_to_hyperlink().
The third parameter is the priority the interrupt, we’ll just give our filter the highest priority though you may wish to experiment with this in a real situation. The default value is 10.

Function Reference: add filter

Description: Hooks a function to a specific filter action.

Usage:
<?php add_filter( $tag, $function_to_add, $priority, $accepted_args ); ?>

Parameters:
$tag (string) (required) The name of the filter to hook the $function_to_add to. (See the Plugin_API/Filter_Reference http://codex.wordpress.org/Plugin_API/Filter_Reference for a list of filter hooks). Default: None
$function_to_add (callback) (required) The name of the function to be called when the filter is applied. Default: None
$priority (integer) (optional) How important your function is (1=highest priority). Alter this to make your function be called before or after other functions. Default: 10.
$accepted_args (integer) (optional) The number of arguments the function(s) accept(s). Default: 1

Return:
The function returns true whether the attempted function hook fails or not.

With the plugin activated WordPress will see this add_filter(the_content) interrupt and send the content of the post to the stipulated function, pk_text_to_hyperlink() in this case. So the content of every post will now be sent through our function, a search made for the target text and if found replaced with the hyperlink before being returned to WordPress for further processing.

Practical Plugin Filter Exercise

Copy Our Plugin Class Template to a New Folder

OK, lets see the code in action.
First we need to create a class for this plugin, so copy the pk-plugin-class template we created previously to a new folder in the wp-content\plugins folder and give it the name pk_text_to_hyperlink.
Open the pk_text_to_hyperlink folder and rename the pk-plugin-class.php file pk_text_to_hyperlink.php.

  • Remember the plugin file name has to be the same name as the folder with the php extention.

Then open the file ready for editing.

Enter a New Plugin Name and Description

The first thing we need to do is enter a new plugin name and description. so that WordPress will recognize the plugin. So change the plugin name and description as follows:

Plugin Name: Text to Hyperlink Demo
Description: A text to hyperlink filter which will search all posts for the stipulated keywords and convert the keywords to hyperlinks.

We now need to create a new class which we’ll call pk_text_to_hyperlink_class. This is simply a case of renaming all occurrences of pk_plugin_template_class to pk_text_to_hyperlink_class. There are six changes to be made.

Enter New Instance Name

Now that we have our plugin class we need an instance of that class. So change the template instance $pk_plugin_demo to a more appropriate name, $pk_text_to_hyperlink_demo.

Enter Text to Hyperlink Function

Next we need to enter the text to hyperlink function, function pk_text_to_hyperlink($content). This should be placed just after the placeholder comment:

// TODO: Enter Action and Filter Methods here

// Change text to hyperlink
function pk_text_to_hyperlink( $content )
{
   $search ="WordPress";
   $replace ="<a title='Permalink to WordPress' href='http://wordpress.org/'>WORDPRESS</a>";
   $content = str_ireplace($search, $replace, $content);
   return $content;
 } // End function pk_text_to_hyperlink

Enter Text to Hyperlink Hook

Next, we need to hook our function into WordPress so enter the add_filter() hook just after the placeholder comment:

// TODO: Enter Plugin Actions and Filters here

// Change text to hyperlink
add_filter('the_content', array(&$this,'pk_text_to_hyperlink'),1);

Save the File

With the code entered, save the file, and see what happens in WordPress.

Login to WordPress as the administrator and navigate to:

  • Dashboard > Plugins > Installed Plugins

to check that our plugin has been recognised but is inactive.

Now, view a post containing the target keyword, “WordPress” in the content prior to our plugin being activated. You should find our target keyword unchanged, neither capitalised nor a hyperlink.

Return to the plugins page and activate our PK Text to Hyperlink Demo plugin.

With that done, return to the post page, and refresh the page. You will see our keyword, “WordPress” has been converted to a hyperlink and capitalised. Just as we planned. Try clicking the link, to check it’s working.
Return to the plugins page and deactivate the plugin ready for the next lesson. With the plugin deactivated return to the post page and refresh the page. You should see the post text return to its original form.

  • This is an important point to note. Our plugin does not modify the text permanently, that is the data in the database is not altered, just the text displayed to the visitor.

Conclusion – Summary

Hopefully this tutorial gave you some insight into what you could do when hooking into WordPress filters. We will be expanding on this lesson by adding a admin interface and saving our keywords and replacement text to the database in latter lessons.

Well, that’s all for this tutorial on How to Write a WordPress Plugin, see you in the next lesson.

Lesson Code – Text to Hyperlink Filter

 <?php
 /*
 Plugin Name: Text to Hyperlink Demo
 Plugin URI: http://kingsolutions.org.uk/wordpress/wordpress/how-to-write-a-wp-plugin/
 Description: A text to hyperlink filter which will search all posts for the stipulated keywords and convert the keywords to hyperlinks.
 Version: 0.1
 Author: Philip King
 Author URI: http://kingsolutions.org.uk/wordpress/
 Licence: Licence GPL2
 */
 /*  Copyright 2011  Philip King  (contact: http://kingsolutions.org.uk/wordpress/)
  This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License, version 2, as
 published by the Free Software Foundation.
  This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
  You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
 /**
 * The Plugin Class
 */
 if (!class_exists("pk_text_to_hyperlink_class")) {
 class pk_text_to_hyperlink_class {
 // TODO: Variable declarations go here

 // TODO: Constructor
 function __construct() {
 // TODO: Enter Plugin Actions and Filters here

 // Change text to hyperlink
 add_filter('the_content', array(&$this,'pk_text_to_hyperlink'),1);
  } // End constructor
  // Core functions go here
 // TODO: Enter Action and Filter Methods here

 // Change text to hyperlink
 function pk_text_to_hyperlink( $content )
 {
 $search ="WordPress";
 $replace ="<a title='Permalink to WordPress' href='http://wordpress.org/'>WORDPRESS</a>";
 $content = str_ireplace($search, $replace, $content);
 return $content;
 } // End function pk_text_to_hyperlink
  // TODO: Enter Helper Methods here

 } // End pk_text_to_hyperlink_class
 } // End if (!class_exists("pk_text_to_hyperlink_class"))
 /**
 * Instantiate (create an instance of) the class
 */
 if (class_exists("pk_text_to_hyperlink_class")) {
 // TODO: Enter New Instance Name
 $pk_text_to_hyperlink_demo = new pk_text_to_hyperlink_class();
 } // End instantiate class
 ?>

KingSolutions.org.uk is hosted on JustHost

  One Response to “131 Text to Hyperlink Filter Example (How-to Video)”

  1. Hello,

    Thank you very much for this incredibly well thought-out and produced series of tutorials. I really appreciate it.

    Wouter

 Leave a Reply

(required)

(required)

91 queries in 1.149 seconds (Child).