Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Using Filters to Alter HTML Output

Posted on January 10, 2012 by Pippin in Action and Filter Hooks, Advanced, Tutorials 2 Comments
Home» Tutorials » Action and Filter Hooks » Using Filters to Alter HTML Output
Tweet
Love It - 0

Filter hooks in WordPress provide a very powerful way to “alter” the output of functions. Using filters we can easily add extra HTML to some functions, and strip HTML from other functions. Some filters, such as the “body_class” filter, allow us to modify the class names of an HTML element, and some filters have nothing to do with HTML at all. The “get_attached_file”, for example, is for modifying the data retrieved by the get_attached_file() function. I’m going to keep with the theme of modifying HTML, since that is what most filter hooks are for, and show you how to setup a custom filter to modify the output from your plugin.

If you’re not familiar with filter hooks, then please consult my Quick Introduction to Using Filter.

Example One – Stripping HTML Tags

Let’s assume, for a moment, that we are outputting some HTML defined by the user, and to ensure that none of that HTML causes problems (such as broken layouts) we want to strip out all non-allowed tags. By this I mean that we’re only going to allow certain HTML tags to be used. The WordPress comments form is a good example of where something like this happens. We also may want to strip out non-allowed tags to prevent malicious code being placed with <script> tags.

So this function will serve as our sample HTML (we can pretend it was defined by a user somewhere):

1
2
3
4
5
6
7
8
9
10
function pippin_sample_html() {	
	ob_start(); ?>	
	<ul>
		<li>List Item <em>One</em></li>
		<li>List <strong>Item</strong> Two</li>
		<li>List Item <a href="#">Three</a></li>
	</ul>	
	<?php
	return ob_get_clean();
}

This is nothing more than a simple unordered list with a few other HTML tags inner mixed.

The HTML from this function is going to be outputted on our site, but before it does, we want to strip out all of the tags that are not allowed. In this case, let’s assume the only allowed tags are <ul> and <li>. To remove all of the other tags, we’re going to pass the HTML through a filter before we echo it. So let’s write the filter function.

1
2
3
4
5
function pippin_strip_tags_filter($html, $preserved_tags = '') {
	$html = strip_tags($html, $preserved_tags);
	return $html;
}
add_filter('pippin_strip_tags', 'pippin_strip_tags_filter', 10, 2);

The function takes two parameters: the HTML to be filtered and a string of the HTML tags we want to preserve. Inside of the function then, we use the strip_tags() function to remove all unwanted tags. At the end, we return our HTML with the unwanted tags removed.

We then use the add_filter() function to attach our pippin_strip_tags_filter() function to a filter hook. Since our filter takes two parameters, instead of the default one, we have to specify the number of accepted arguments.

So now, to output our HTML with the unwanted tags removed, we can do this:

1
2
$html = pippin_sample_html();
echo apply_filters('pippin_strip_tags', $html, '<ul><li>');

The final result will be:

1
2
3
4
5
<ul>
	<li>List Item One</li>
	<li>List Item Two</li>
	<li>List Item Three</li>
</ul>

Example Two – Adding a Wrapper to Existing HTML

For this example, let’s use the same HTML as we did before:

1
2
3
4
5
6
7
8
9
10
function pippin_sample_html() {	
	ob_start(); ?>	
	<ul>
		<li>List Item <em>One</em></li>
		<li>List <strong>Item</strong> Two</li>
		<li>List Item <a href="#">Three</a></li>
	</ul>	
	<?php
	return ob_get_clean();
}

Now let us suppose that we want to add some wrapper HTML around the output of our pippin_sample_html() function. Let’s start with our filter function:

1
2
3
4
5
6
function pippin_add_html_wrapper($html, $begin, $end) {
	// wrap our original HTML with the new tags
	$html = $begin . $html . $end;
	return $html;
}
add_filter('pippin_html_wrap', 'pippin_add_html_wrapper', 10, 3);

The function takes three arguments:

  1. The HTML to wrap
  2. The HTML to use as the opening wrapper tag
  3. The HTML to use as the closing wrapper tag

Inside of the function we simply combine the three parameters, and then return it.

So to output our sample HTML with a custom wrapper, we use this:

1
2
$html = pippin_sample_html();
echo apply_filters('pippin_html_wrap', $html, '<div id="sample_wrapper">', '</div>');

Both of the examples I’ve shown you here are pretty simple, but very powerful at the same time. Filters can be used for all sorts of things, so I encourage you to be creative and play around with them.

Tweet Follow @pippinsplugins
add_filter, apply_filters, filter, hook

2 comments on “Using Filters to Alter HTML Output”

  1. adambundy says:
    January 10, 2012 at 9:39 am

    Pippin, would you kindly stop writing such informative, useful blog posts? I’m spending too much time reading your posts and not getting much work done. Thank you kindly.

    Reply
    • Pippin says:
      January 10, 2012 at 9:40 am

      I suppose I could . . . but then I would be slacking off and not you! :)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Plugin Development 101 – An Intro to Filters
  • Introduction to the gettext Filter in WordPress
  • Let’s Talk Extensible Code
  • Playing Nice with the “the_content” Filter
  • Adding Custom Fields to the Easy Digital Downloads Checkout

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (2)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • @jaredatch @kimparsell :D
    May 23, 2013
  • @jaredatch there is, as long as there is at least one ticket
    May 23, 2013
  • RT @Astoundify: We are hiring p/t tech support rep for our support forum if your interested email contact [at] http://t.co/bcXNhcwZx5
    May 23, 2013

Topics

hook meta box Rémi Corson featured shortcodes campaign monitor add_options_page register_setting Sugar Event Calendar attachments add_shortcode wp_enqueue_script the_content image forms short codes Related posts login do_action authors mail chimp attachment plugin recent posts comments post types bbpress apply_filters short code taxonomies custom post type Ajax images gallery Stripe jquery taxonomy users widgets add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2011 Pippin's Plugins