使用多个查询POST循环生成动态标签

时间:2012-07-28 作者:user1305063

我正在尝试生成一个基于动态选项卡的导航查询邮递代码如下

            <div class="tabbable">
            <ul class="nav nav-tabs">
            <?php
            $my_query = new WP_Query(array(
            \'showposts\' => 5,
            \'orderby\' => \'rand\',
            \'category_name\' => \'Recipes\'
            ));
            $x = 0;
            while ($my_query->have_posts()) : $my_query->the_post(); $x++; 
            $category = get_the_category(); 
            ?>          
            <?php if ($x == 1) { echo \'<li class="active">\'; } else {echo \'<li>\';} ?>
            <a href="#tab<?php echo $x; ?>" data-toggle="tab"><?php echo $category[0]->cat_name; ?></a></li>
            <?php endwhile;?>     
            </ul>

            <div class="tab-content">
            <div class="tab-pane active" id="tab1">
              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. .</p>
            </div>
            <div class="tab-pane" id="tab2">
              <p>Ut consectetur libero nec nulla ullamcorper lobortis pulvinar libero viverra.</p>
            </div>
            <div class="tab-pane" id="tab3">
              <p>Vivamus eget velit at mauris blandit consequat vel sed ipsum.</p>
            </div>
            </div>
            </div>
这一切正常,工作正常,问题是上述代码可以重复任何特定类别。例如,它可以显示

cat1     cat2     cat3    cat1   cat2
这是我不想要的,我需要任何类别不再重复。如何克服这个问题?

请记住,在第二阶段中,我将使用rewind\\u post()从上述类别中获取数据,因此我希望保持循环内联

非常感谢。

好的,我已经更新了我的代码如下

            <div class="tabbable">
            <ul class="nav nav-tabs">
            <?php
            $my_query = new WP_Query(array(
            \'showposts\' => 3,
            \'orderby\' => \'rand\',
            \'category_name\' => \'Recipes\'
            ));
            while ($my_query->have_posts()) : $my_query->the_post();
            $x = $my_query->current_post + 1;  //use this to count instead
            $categories = get_the_category();
            foreach($categories as $category) {
            if ($x == 1) { echo \'<li class="active">\'; } else {echo \'<li>\';} ?>
            <a href="#tab<?php echo $x; ?>" data-toggle="tab"><?php echo $category->cat_name; ?></a></li>
            <?php
            }
            endwhile;
            ?>  
            </ul>
现在,我如何在选项卡内容部分显示每个类别中的4个食谱

1 个回复
SO网友:Wyck

你需要做一个foreach 对于get_the_category

类似于:

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

$x = $my_query->current_post + 1;  //you can use this to count instead
$categories = get_the_category();

foreach($categories as $category) {
 if ($x == 1) ...
//rest of your output
// remember to us $category->cat_name; instead of what you have above
}

结束

相关推荐

get_meta_data within a loop

我试图制作一个简单的小部件,它显示一个帖子列表,后面是每个帖子的一些元数据。这是我的代码:$eventdate 包含我需要检索的元数据。query_posts(\'\'); if (have_posts()) : echo \"<ul>\"; while (have_posts()) : the_post(); $eventdate = get_post_meta($post->ID, \'event-date