5

Which hook or filter is used to edit the post content before the_content filter is applied to it.

For instance, if I wanted to add Hello World, as the first text in every post.

6

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' );
   }
} );
  • 1
    in which file should you add this code? – Uri Abramson May 2 '18 at 12:46
1

There is no other global filter applied before the_content - you can use the $priority argument in your add_filter call to ensure your function runs before any others:

function wpse_225625_to_the_top( $content ) {
    return "Hello World\n\n\$content";
}

add_filter( 'the_content', 'wpse_225625_to_the_top', -1 /* Super important yo */  );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.