Adsense Ad at Random Position in a Posts Page

This code is made to output an adsense ad (or any other block of output) at a random position within the loop, with the restriction to a preset number of possible positions.

<?php $ad_positions = array(1,2,4); // array of preset possible ad positions

do { $rnd_ad = $ad_positions[rand(0,count($ad_positions)-1)]; } while ($rnd_ad >= $wp_query->post_count); 
// to make sure that the random output fits into the available number of posts ?>

<?php if(have_posts()) : while(have_posts()) : the_post(); // start of the loop // ?>

some part of the post output here

  <?php if( ($wp_query->current_post+1) == $rnd_ad ) : ?>
    adsense code here
  <?php endif; ?> 

more post output here

<?php endwhile; endif; // end of the loop // ?>

Thanks to the tutorials of …

Numbering Posts

To give posts a continuous number in index pages or archives, try this little piece of code:

global $query_string;
  $all_post_query = new WP_Query($query_string.'&posts_per_page=-1');
    $count_posts = $all_post_query->post_count;
  $this_post_nr = 1 + $wp_query->current_post + (get_query_var('paged')?(get_query_var('paged')-1) : 0) * get_option('posts_per_page');
echo $this_post_nr.' of '.$count_posts.' in this selection of posts.';

Place it within the loop;
condition: needs to be adjusted for any custom query.

Twenty Eleven – New Page Template with Sidebar Correction

If you are creating a new page template for a child theme of Twenty Eleven, with a sidebar, you need to correct the body_class output to remove the css class .singular.

Add this to functions.php of your child theme:

add_filter('body_class', 'adjust_body_class', 20, 2);  
function adjust_body_class($wp_classes, $extra_classes) { 

if( is_page_template('new-sidebar-page-template-file-name.php') ) : 
// Filter the body classes     
	  foreach($wp_classes as $key => $value) {
	  if ($value == 'singular') unset($wp_classes[$key]);
// Add the extra classes back untouched
return array_merge($wp_classes, (array) $extra_classes ); 

If you created more than one new page template with sidebar, change this one line in the code to something like:

if( is_page_template('new-sidebar-page-template-file-name.php') || is_page_template('another-sidebar-page-template.php') || is_page_template('further-sidebar-page-template.php') ) :

The above codes are similar to what I used in this recent article.