Skip to content

Instantly share code, notes, and snippets.

@Garconis
Created August 23, 2018 17:55
Show Gist options
  • Save Garconis/d5541fb29e7daf0d2c45c7f63b22e713 to your computer and use it in GitHub Desktop.
Save Garconis/d5541fb29e7daf0d2c45c7f63b22e713 to your computer and use it in GitHub Desktop.
WordPress | Inject a new custom post type posting into the loop every X amount of regular posts
<?php
add_action( 'wp', 'fs_only_do_on_homepage' );
function fs_only_do_on_homepage() {
if( is_front_page() ) {
/* change the query to inject ads after every X frequency */
// https://www.gowp.com/blog/inserting-custom-posts-loop/
add_filter( 'the_posts', 'fs_insert_ads', 10, 2 );
function fs_insert_ads( $posts, $query ) {
// We don't want our filter to affect post lists in the admin dashboard
if ( is_admin() ) return $posts;
// We also only want our filter to affect the main query
if ( ! is_main_query() ) return $posts;
// Set a variable for the frequency of the insertion which we'll use in some math later on
$freq = 2;
/* Retrieve the ads, and calculate the posts_per_page on the fly,
* based on the value from the original/main query AND our frequency
* this helps ensure that the inserted posts stay in sync regardless of pagination settings
*/
$args = array(
'post_type' => 'fs_ads',
'posts_per_page' => floor( $query->query_vars['posts_per_page'] / $freq ),
'paged' => ( $query->query_vars['paged'] ) ? $query->query_vars['paged'] : 1,
'orderby' => 'menu_order',
'order' => 'ASC',
'meta_key' => 'status',
'meta_value' => 'enable',
);
// inserts the ads into the $posts array, using array_slice() ... and do some math to ensure they are inserted correctly
if ( $fs_ads = get_posts( $args ) ) {
$insert = -1;
foreach ( $fs_ads as $fs_ad ) {
$insert = $insert + ( $freq + 1 );
array_splice( $posts, $insert, 0, array( $fs_ad ) );
}
}
return $posts;
} // end the fs_insert_ads function
} // end checking is_home
} // end the fs_only_do_on_homepage function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment