Wordpress - 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' );
}
} );
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 */ );