Close
Menu

RTCXpression

Content Filters in WordPress – Functions to Massage the Content


August 1, 2017

WordPress functions are easy to add to a WordPress theme. A function to massage the content for a post, page or feed is easy to create. One becomes many, once you see how powerful it is.

More than a decade after I used WordPress for the first time, I’m still discovering things. I knew about “the_content” filter for posts and pages, but I only guessed about the others.

The WordPress Filter Reference and Content Filters

If you visit the WordPress Filter Reference in the WordPress Codex, you can find the content filters spread out within the list. The most commonly used filter is for “the_content” function, but here’s the list of the few you should look at:

The WordPress Function

The function for each filter works exactly the same way. Only the function names are different. Here are three examples for “the_content”:

function insert_before_content($text) {
  $text = "some text" . $text;
  return $text;
}
add_filter('the_content', 'insert_before_content');

function replace_some_content($text) {
  $text = str_replace('some text', 'some other text', $text);
  return $text;
}
add_filter('the_content', 'replace_some_content');

function add_to_content($text) {
  $text .= 'some text';
  return $text;
}
add_filter('the_content', 'add_to_content');

You can use almost anything instead of the variable “$text” (like “$content” or “$entry”).

You can place the “add_filter” line before or after the function, your preference. Assign priorities (the default is 10) by adding numbers, like this:

add_filter('the_content', 'insert_before_content', 9);
add_filter('the_content', 'replace_some_content', 10);
add_filter('the_content', 'add_to_content', 11);

The Content Filter Functions I Use

I’m using fewer filters with my custom WordPress theme than I would with an approved WordPress theme. I simply echo everything that comes after the text: The social sharing links, the categories and tags, the previous and next links, AdSense ads and Disqus comments.

I replace some content with content filters, but the main one is when I replace an HTML comment line with an AdSense ad between paragraphs. Yes, I manually enter this line in some posts (but not this one because it’s too short):

<!--adsense-paragraph-->

My content filter function replaces it with a real ad. Why do it this way and not just enter the real ad itself to begin with? Well, because I sometimes change the format. I don’t want to spend more time editing older posts than I have to.

Please go to this alternate page if you would like read or post comments.

Share:

Categories: Technology

Tags: , ,

Previous and Next Articles (if any):

« »

More

Please read some of my more important pages if you have the time:

Comments Policy           Privacy Policy

RTCXpression established Feb 28, 2011
Copyright © 2013-2017 RT Cunningham
Hosted at Digital Ocean