Dev Notes

Software Development Resources by David Egan.

WordPress Filter Hooks


WordPress
David Egan

Filters can operate on content snippets or on arrays.

Filters are the hooks that WordPress launches to modify text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API.

WordPress Codex

To set up content for filtering, use the apply_filters() function:

<?php apply_filters( $tag, $value, $var ... ); ?>

Create the Hook

Apply filters attached to ‘custom_content_filter’ to $content. This would be typically added to a template file:

$content = apply_filters ( 'custom_content_filter', 'alert alert-info' );

Create Filter

Create the filter and attach to the filter hook. Typically in custom functions file.

function carawebs_wrap_content( $content, $div_class ) {

    if ( 'blockquote' == $wrap_tag ) {

        return "<blockquote>" . $content . "</blockquote>";

    } else {

        return "<div class='$div_class'>" . $content . "</div>";

    }

}

// Filter the content passed in from 'custom_content_filter' with the
// specified callback function - in this case, 'carawebs_wrap_content'.

add_filter ( 'custom_content_filter', 'carawebs_wrap_content' );

WordPress Filters

There are many built-in WordPress filters. For example, ‘the_content’ filters content after database retrieval and before printing to the screen. To use this filter, it’s simply a matter of passing the content. This can be very useful when fetching post content outside the loop using get_the_content() - which returns unfiltered content.

$raw_content = get_the_content( $current_ID );
$filtered_content = apply_filters( 'the_content', $raw_content );

Filter functions can be added using the add_filter() function. For example, this function prepends a post thumbnail to the $content passed in to the ‘the_content’ filter - which is usually the post content:

// From WP Codex.
// @see: https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content

add_filter( 'the_content', 'featured_image_before_content' );

 function featured_image_before_content( $content ) {

    if ( is_singular('post') && has_post_thumbnail()) {

        $thumbnail = get_the_post_thumbnail();
        $content = $thumbnail . $content;

		}

    return $content;
}

From WP Codex.

Resources


comments powered by Disqus