Call the_content filter once and only once
Did you know that your the_content
filter is being called multiple times? Here's how to ensure your filter function is called once.
If you hook into the the_content
filter to modify a blog post's content, you may notice that the hook gets executed more than one time. This can cause your page load time to increase. The code below is an example of how to ensure your the_content
filter function is called once and only once during the page load of a single WordPress Post|Page|Product|etc...
/**
* Example of how to execute the "the_content" filter ONLY once.
*
* @param string $content
*
* @return string $content
*/
function mycode_the_content( $content ) {
if ( ! in_the_loop() ) {
return $content;
}
if ( ! is_singular() ) {
return $content;
}
if ( ! is_main_query() ) {
return $content;
}
$content = ucwords( $content );
remove_filter( current_filter(), __FUNCTION__ );
return $content;
}
add_filter( 'the_content', 'mycode_the_content' );
Last updated on April 2021