How to create a plugin that only operates on the home page?

I have a plugin that I only want to execute when the home page is being viewed. How would I stub out my plugin in order to make this happen?

This is does not work…

 <?php
 /*
 Plugin Name: My Test Plugin
 */


 if ( is_home() OR is_sticky() )
 {
  add_filter( 'the_content', 'my_function' );
 }

 function my_function( $content )
 { 
  echo "hello world".$content;
 }

 ?>

This is my original code, but it executes the filter on every page. Which seems overkill to me, since I only want the plugin to run on the home page anyway.

 add_filter( 'the_content', 'wpse6034_the_content' );
 function wpse6034_the_content( $content )
 {
  if ( is_home() ) {
   $content .= '<p>Hello World!</p>';
  }
  return $content;
 }

1 Answer
1

You need to add the filter later:

function _add_my_filter() {
 if ( is_home() OR is_sticky() )
 {
  add_filter( 'the_content', 'my_function' );
 }
}
add_action('template_redirect', '_add_my_filter');

Leave a Comment