Where to hook into post content?

You can use the_content with an high prioriety (lower number).

add_filter( 'the_content', function( $content ) {
  return 'Hello World '.$content;
}, 0);

You can even use negative priority:

add_filter( 'the_content', function( $content ) {
  return 'Hello World '.$content;
}, -10);

Note that this will apply everytime 'the_content' is used, no matter the post type, or if the target post is part of main query or not.

For more control you can use loop_start / loop_end actions to add and remove the filter:

// the function that edits post content
function my_edit_content( $content ) {
  global $post;
  // only edit specific post types
  $types = array( 'post', 'page' );
  if ( $post && in_array( $post->post_type, $types, true ) ) {
     $content="Hello World ". $content;
  }

  return $content;
}

// add the filter when main loop starts
add_action( 'loop_start', function( WP_Query $query ) {
   if ( $query->is_main_query() ) {
     add_filter( 'the_content', 'my_edit_content', -10 );
   }
} );

// remove the filter when main loop ends
add_action( 'loop_end', function( WP_Query $query ) {
   if ( has_filter( 'the_content', 'my_edit_content' ) ) {
     remove_filter( 'the_content', 'my_edit_content' );
   }
} );

Leave a Comment