Call the_content filter once and only 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…

<?php /** * 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' );

Leave a Reply

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