Inject post (from specific category) between posts in Loop

The Automatic Sponsor Posts Injector:

Here’s one idea based on my answer for the question:
How to show Y number of custom posts after every X normal posts?

I hopefully made it a little bit more useful here on Github, but it may be refined much more (future work).

The SponsorPostsInjector class will help you to automatically inject the sponsor posts into the theme using the filters the_post, loop_start and loop_end.

Activate the plugin and add the following example to your functions.php file to start the injections:

/**
 * Inject a sponsor post after the first post on the home page,
 * and then again for every third post within the main query.
 */

add_action( 'wp', 'my_sponsor_injections' );

function my_sponsor_injections()
{
    if( ! class_exists( 'SponsorPostsInjector' ) ) return;

    // We want the sponsor posts injections only on the home page:
    if( ! is_home()  ) return;

    // Setup the injection:
    $injector = new SponsorPostsInjector( 
        array(
            'items_before_each_inject' => 3,
            'items_per_inject'         => 1,
            'template_part'            => 'content-sponsor',
        ) 
    );

    // Setup the injection query:
    $injector->query(
        array(
            'post_type'  => 'sponsor',
            'tax_query'  => array( 
                array(
                   'taxonomy' => 'country',
                    'terms'   => 'sweden',    
                    'field'   => 'slug', 
                )
            )
        )
    );

    // Inject:
    $injector->inject();
}

where we have created the content-sponsor.php template file in our current theme directory, to control the layout of the injected sponsor posts.

The idea is that this should also take care of the pagination.

You can hopefully adjust this to your needs.

Leave a Comment