Skip to content

Commit

Permalink
Inject post in loop_start instead of the_posts
Browse files Browse the repository at this point in the history
  • Loading branch information
cphilleo committed Apr 18, 2023
1 parent 5f29024 commit 63b8795
Showing 1 changed file with 10 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ class WordAds_Sponsored_Post {
*/
public static function init() {
// Inject the sponsored post.
add_filter( 'the_posts', array( __CLASS__, 'inject_sponsored_post' ), 10, 2 );
add_action( 'loop_start', array( __CLASS__, 'amp_fix' ) );
add_action( 'loop_start', array( __CLASS__, 'inject_sponsored_post' ) );

// Override post display.
add_filter( 'post_class', array( __CLASS__, 'add_post_class' ), 10, 3 );
Expand Down Expand Up @@ -59,16 +58,20 @@ public static function init() {
/**
* Inject the sponsored post into the WP query
*
* @param array $posts Array of posts that are part of the query.
* @param WP_Query $wp_query The WP_Query.
*
* @return array Array of Posts.
*/
public static function inject_sponsored_post( $posts, $wp_query ) {
public static function inject_sponsored_post( $wp_query ) {

// Don't run on AMP pages.
if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {
return;
}

// Only inject on main front page query.
if ( ! ( is_front_page() && $wp_query->is_main_query() ) ) {
return $posts;
return;
}

$dummy = new stdClass();
Expand All @@ -84,42 +87,8 @@ public static function inject_sponsored_post( $posts, $wp_query ) {
$dummy_post = new WP_Post( $dummy );
wp_cache_add( $dummy->ID, $dummy_post, 'posts' );

$posts[] = $dummy_post;

return $posts;
}

/**
* Removes sponsored post from the query when running AMP.
*
* @param WP_Query $wp_query The WP query.
*
* @return void
*/
public static function amp_fix( $wp_query ) {
/*
* The purpose here is to remove the sponsored post when AMP is enabled so it's not rendered to the page.
* This is a bit janky. We need to inject the sponsored post in the_posts hook, but at that point in time
* AMP hasn't been initialized yet to check if it's active. So here we hook the main loop and if AMP is
* enabled we remove the sponsored post and fixup the post count.
*/

if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) {

if ( 0 === count( $wp_query->posts ) ) {
return;
}

foreach ( $wp_query->posts as $index => $post ) {
if ( self::POST_ID === $post->ID ) {
unset( $wp_query->posts[ $index ] );
--$wp_query->post_count;
}
}

// Re-index the array in case we unset a post.
$wp_query->posts = array_values( $wp_query->posts );
}
$wp_query->posts[] = $dummy_post;
++$wp_query->post_count;
}

/**
Expand Down

0 comments on commit 63b8795

Please sign in to comment.