如何在QUERY_POSTS中第N个帖子之后放置图像

时间:2012-10-23 作者:Andy M

我正在使用以下代码以3so 3列和3行的列打印最后8篇发表的文章:

<?php
  $args = array(
               \'post_type\' => \'post\',
               \'posts_per_page\' => 8,
               \'paged\' => ( get_query_var(\'paged\') ? get_query_var(\'paged\') : 1)
               );
  query_posts($args);
  $x = 0;
  while (have_posts()) : the_post(); ?>    

    <?php if($x == 2) { ?>
    <div class="portfolio_list_box portfolio_list_last">
    <?php } else { ?>
    <div class="portfolio_list_box">
    <?php } ?>
      <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(\'featured-home-portfolio\'); ?></a>
      <a href="<?php the_permalink(); ?>"><h2><?php the_title(); ?></h2></a>
      <?php the_excerpt(); ?>
    </div><!--//portfolio_list_box-->  

    <?php if($x == 2) { echo \'<div class="clear"></div>\'; $x = -1; } ?>

  <?php $x++; ?>
  <?php endwhile; ?>
  <?php wp_reset_query(); ?> 
现在我想在第五篇文章后面放一张图片。这是第2行第3列。我修改了很多次这段代码,但我不能让这张图片只在第5篇文章之后显示出来。

我添加了以下内容:

<?php if($x == 2) { ?>
    <div class="portfolio_list_box portfolio_list_last">
    <?php } elseif($x == 5) { ?>
 // image 
<?php } else { ?>
但不起作用。如果有人能帮我解决这个问题,我真的很感激。谢谢

2 个回复
最合适的回答,由SO网友:Wyck 整理而成

多重嵌套if 语句可能会造成混乱,您可以使用switch 对于这种情况。

类似于:

  //your $args
  $the_switch_query = new WP_Query($args);

  while ( $the_switch_query ->have_posts() ) : $the_switch_query ->the_post(); 

  $query_number = $the_switch_query->current_post + 1; //count them

       switch ($query_number){

             case 1;
             echo "post one";
             break;

             case 5;
             echo "post five";
             break;

            // more cases

            default:
            echo "default";
        }
       //rest of your stuff

SO网友:Milo

这实际上只是一个php问题。它永远不会达到5,因为当它等于2时,你将x重置为-1

<?php if($x == 2) { echo \'<div class="clear"></div>\'; $x = -1; } ?>

结束

相关推荐