You can use the loop_start
hook which passes the $WP_Query
object by reference.
namespace StackExchange\WordPress;
class editFirstPostContent {
public function load() {
if( \is_admin() ) {
return;
}
\add_filter( 'loop_start', [ $this, 'loopStart' ] );
}
public function loopStart( \WP_Query $WP_Query) {
if( ! $WP_Query->is_main_query() ) {
return;
}
if( ! isset( $WP_Query->posts[0] ) ) {
return;
}
$WP_Query->posts[0]->post_content = sprintf(
'<div>Hello World!</div>%1$s',
$WP_Query->posts[0]->post_content
);
}
}
$editFirstPostContent = new editFirstPostContent();
\add_action( 'plugins_loaded', [ $editFirstPostContent, 'load' ] );