Skip to content

Instantly share code, notes, and snippets.

@zogot
Last active December 26, 2015 05:19
Show Gist options
  • Save zogot/7100237 to your computer and use it in GitHub Desktop.
Save zogot/7100237 to your computer and use it in GitHub Desktop.
Easily add posts into certain positions on WP_Query. Adverts example.
<?php
add_action( 'pre_get_posts', 'kwpn_advert_positions_pre_get_posts', 20 );
function kwpn_advert_positions_pre_get_posts( WP_Query $query ) {
// Only continue if the query chose to have adverts
if ( ! is_array( $query->get( 'kwpn_insert_adverts' ) ) )
return;
// Get the chosen advert positions
$advert_positions = $query->get( 'kwpn_insert_adverts' );
$total_adverts = count( $advert_positions );
// Get the adverts
$advert_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => $total_adverts,
'paged' => ( $query->get( 'paged' ) ? $query->get( 'paged' ) : 1 ),
'meta_query' => array(
array(
'key' => '_kwpn_advert',
'value' => 1
)
)
) );
// Determine how many adverts were found
$found_adverts = $advert_query->post_count;
// Get the posts_per_page, and minus how many found adverts
$posts_per_page = $query->get( 'posts_per_page' );
// No posts per page specified, get the default
if ( empty( $posts_per_page ) )
$posts_per_page = get_option( 'posts_per_page' );
$query->set( 'posts_per_page', $posts_per_page - $found_adverts );
// Remove the option to get adverts in the post list
$query->set( 'meta_query', array(
array(
'key' => '_kwpn_advert',
'value' => '',
'compare' => 'NOT EXISTS'
)
) );
// If something other than 0 were found, set the advert query
if ( 0 !== $found_adverts )
$query->set( 'kwpn_insert_advert_query', $advert_query );
}
add_filter( 'the_posts', 'kwpn_advert_positions_the_posts', 10, 2 );
function kwpn_advert_positions_the_posts( $posts, WP_Query $query ) {
// Only continue if the query chose to have adverts
if ( ! is_array( $query->get( 'kwpn_insert_adverts' ) ) )
return $posts;
// Get the chosen advert positions
$advert_positions = $query->get( 'kwpn_insert_adverts' );
// Get the advert query
$advert_query = $query->get( 'kwpn_insert_advert_query' );
// If no advert query is set, then there are no adverts, so just return all posts
if ( empty( $advert_query ) )
return $posts;
// Get the advert queries posts
$advert_posts = $advert_query->posts;
// Go through each in array of advert positions
foreach ( $advert_positions as $key => $advert_position ) {
if ( isset( $advert_posts[$key] ) )
array_splice( $posts, $advert_position, 0, array( $advert_posts[$key] ) );
}
return $posts;
}
add_action( 'pre_get_posts', 'kwpn_adverts_home_page' );
function kwpn_adverts_home_page( WP_Query $query ) {
if ( $query->is_home() && $query->is_main_query() )
$query->set( 'kwpn_insert_adverts', array( 1, 5 ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment