I have a view that output the content nodes as grid. (instigram style). How to insert an advertisement block in a random location within the views list.

Node Node . . Advertisement . . Node Node

  • I think you must use the views hooks after generating result. then count the result's rows and select the random position between rows , finally you must load your advertisement block and insert it into the #markup nodes in the selected rows. For this issue, module programming is needed buy maybe the other friends can help you to do it only with views definition.
    – Mehrdad201
    Commented Feb 11, 2014 at 7:37

2 Answers 2


You can override the format specific template like views-view-unformatted.tpl.php (you can find the right file based on your requirement) and then use some custom code like

  <?php if (($id % 2) == 0): ?>
    Do what-ever you want to do here. 
  <?php endif; ?>

This module hosted on github https://github.com/pedroposada/custom_views_nthrow seems to do the same more modularly.

Instructions : http://www.pedroposada.com/blog/insert-whatever-every-nth-row-views.html-0

  • 1
    Thx !! Just what i needed !! i ended overriding "views-view-unformatted.tpl.php" and inserting the ad block in a random location wihin the loop.
    – Zorox
    Commented Feb 11, 2014 at 8:19

If you want to have your custom code after first row then override your default views-view-unformatted.tpl.php with this code:

<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  <?php if ($id == 0 || $id == 5): ?>
Your custom adsense code
  <?php endif; ?>
<?php endforeach; ?>

Step-by-step tutorial for newbies on how to override default views-view-unformatted.tpl.php and achieve custom code after for example first and sixth row is here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.