Webtecho Blog

WordPress filters explained

in General

Hooks and filters are often talked in same jest. However they perform a totally different set of tasks.

While a hook allows you to insert your own code into selected places in the wordpress layout for e.g. header or footer, filters actually allow to modify what content is being printed on the browser. The primary examples are the content of the post and content of the comment.

Let us take an example. You have a blog which contains a number of posts. You have found that one of the ways that you can get more comments is to ask them, if they like the post and what are their views on it.

“Did you like the post above ? Do you have any comments on it? Would you like to share them with me?

Unfortunately your blog posts number in tens . It is not easy for you to go and add each the above comment to each and every line and then republish them and check them again.

Fortunately a filter will help you to do exactly that.

If you want to modify content before it is displayed on your site, you may use the filter called as ‘the_content’ and attach your function to it.

add_filter(‘the_content’,’your_function_to_modify_content’);

function your_function_to_modify_content($post_text)

{

$post_text = $post_text. ‘<p>Did you like the post above ? Do you have any comments on it? Would you like to share them with me?</p>;

return $post_text';

}

Place the above code in the functions.php in your wordpress theme and see the fun. This line will be added to all the posts of your blog.

This is used by a large number of plugins which want to modify or add to your content. You see that there is an argument ‘post_text’. You may chose to name it anything else.

The important thing is to return it to the calling function after modification, otherwise you will see no content in the blog. Do not worry, the content is not wiped off from database. It is just not being displayed. So be careful and return the $post_text to make sure WordPress prints your content on the browser.

{ 0 comments… add one now }

Leave a Comment

Current ye@r *

Previous post:

Next post: