What are Filters in WordPress?

136. What are filters in WordPress

Filters are functions which WordPress passes data through, at certain points in execution, just before taking some action with the data (like adding it to the database or sending it to the browser screen). Filters are between the database and the browser, and between the browser and the database; most input and output in WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin may add its own filtering.

The basic steps to add your own filters to WordPress are:

  1. Create the PHP function that filters the data.
  2. Hook to the filter in WordPress, by calling add_filter().
  3. Put your PHP function in a plugin file, and activate it.

A filter function takes as input the unmodified data, and returns modified data. If the data is not modified by your filter, the original data has to be returned so that subsequent plugins can continue to modify the value if necessary.

So, the first step in creating a filter in your plugin will be creating a PHP function to do the filtering, and puting it in your plugin file. For example, if you need to make sure that your posts and comments contain no profanity, you might define a variable with a list of forbidden words, and then create the following PHP function:

function filter_profanity( $content ) { $profanities = array(‘badword’,’alsobad’,’…’); $content = str_ireplace( $profanities, ‘{censored}’, $content ); return $content; }

Just keep in mind that other plugins or the WordPress core may already be using the function name you have thought of.

Hope you liked this article, guys!

Share this!

Post Author: Staff

Leave a Reply

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