Hook into the loop via a plugin, and output something after every X post?

I have a plugin where I want to output ads after X number of posts on the home page. The home page is step 1, but things like archives should be possible too once I get the code for the home page.

How do I hook in to post loops and say something like “after every loop, increment a counter, and then if the counter = my number, output an ad”. I can write all the logic for this code myself, but where to hook/implement my code is confusing.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can try the following:

Method 1:

We can inject the ads via the the_post action, in the main loop:

add_action( 'loop_start', 'wpse_141253_loop_start' );

function wpse_141253_loop_start( $query )
{
    if( $query->is_main_query() )
    {
        add_action( 'the_post', 'wpse_141253_the_post' );
        add_action( 'loop_end', 'wpse_141253_loop_end' );
    }
}

function wpse_141253_the_post()
{
    static $nr = 0;

    if( 0 === ++$nr % 4 )
        echo '<div> -------- MY AD HERE ------- </div>';
}

function wpse_141253_loop_end()
{
    remove_action( 'the_post', 'wpse_141253_the_post' );   
}

Method 2:

We can also inject the ads via the the_content filter, in the main loop:

add_action( 'loop_start', 'wpse_141253_loop_start' );

function wpse_141253_loop_start( $query )
{
    if( $query->is_main_query() )
    {
        add_filter( 'the_content', 'wpse_141253_the_content' );
        add_action( 'loop_end', 'wpse_141253_loop_end' );
    }
}

function wpse_141253_the_content( $content )
{
    static $nr = 0;

    if( 0 === ++$nr % 4 )
        $content .= '<div>------- MY AD HERE -------</div>';

    return $content;
}

function wpse_141253_loop_end()
{
    remove_action( 'the_post', 'wpse_141253_the_content' );   
}

Hopefully you can modify this to your needs.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x