Insert Ad Code After X Number of Posts – WordPress

Advertisement

In this tutorial I’d like to share you how we can add ad code after x number of posts in custom query or in pagination, mostly as a blog author we choose single, page and sidebar to display our ads, right after the title or after the post content but if you’d like to display ads in many different places to maximize ad revenue then this tutorial is right for you folks.

Custom Query Code


<?php
// declare counter variable
$c = 0;

$args = array(
'post_type' => 'post'
);

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {

	while ( $the_query->have_posts() ) { $the_query->the_post();
		// increment our counter variable
		$i++;


		// let's see you'd like to add the ad right before the loop content
		// we begin with if condition, e.g. if we'd like to display ad in first row and in the third row
		if( 1 == $i || 3 == $i ) {
			// add your code here
		}

		?>
			<div class="entry">
				<h2><?php the_title(); ?></h2>

				<?php the_content('read more'); ?>
			</div>
		<?php
	}
       } else {
	// no posts found
}

/* Restore original Post Data */
wp_reset_postdata();

On Pagination

To add code on navigation, here’s how.

On sub-pages we can simply add the below code to get current paged string, actually, we really need the code below to get current pager number and use in pagination.


$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

or


// static page or front-page
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;

// In the above custom query replace the <code>if condition

If you don’t know yet how to add pagination on both custom post-type and default post-type visit this page Custom Post-type Pagination

That’s it, happy coding ^_^

Advertisement