WordPress循环:如果帖子存在,则显示<div>

时间:2012-02-19 作者:sarytash

在一个帖子模板中,我试图在<div> 并在<ul> 如果存在相关帖子(基于标签)。如果没有帖子,则不应显示任何内容。$idspost[] = $post->ID 获取应显示的帖子。循环是一系列循环中的一个,检索到的帖子ID也会传递给下一个循环,以避免出现重复的帖子。到目前为止,一切都很顺利。我已经呼出了要测试的ID,但以我的基本技能,我不知道我将如何显示<div>,<ul> 并以标准方式检索帖子ID:

<?php if (have_posts()) : ?>
  <div>
    <?php while (have_posts()) : the_post(); ?>
      … //get the permalink, title etc...
    <?php endwhile; ?> 
  </div>
<?php endif; ?>
检索帖子ID:

<?php
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
      $second_tag = $tags[1]->term_id;
      $args=array(
        \'tag__in\' => array($second_tag),
        \'post__not_in\' => array($post->ID),
        \'showposts\'=>5, //Display this number of related posts
        \'ignore_sticky_posts\'=>1
       );
      $my_query = new WP_Query($args);
      if( $my_query->have_posts() ) {
          while ($my_query->have_posts()) : $my_query->the_post(); 
          if (!in_array($post->ID, $ids)) 
          {; $idspost[] = $post->ID; ?>

    <?php }
        $ids[]= $post->ID; 
        $idspost[] = $post->ID;
        endwhile;
      }
    }
    ?>
非常感谢您的帮助!

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

为了将数组中的数据输出为POST,我执行了以下操作:

<?php
  if(count($idspost)){
    echo "<div>Related posts<ul>";
    foreach($idspost as $id){
       echo \'<li><a href="\'.get_permalink( $id ).\'">\'.get_the_title( $id ).\'</a></li>\';
    }
    echo "</ul></div>";
  }
?>  

SO网友:Jeremy Jared

您可以在条件语句中使用has\\u tag函数来实现所需的功能。请查看此处的codex页面:Function Reference/has tag.这并不是完全针对您的特定问题量身定制的,但您应该了解它的工作原理,并根据您的特定任务进行调整:

<?php if( has_tag() ) { ?>
<?php query_posts( \'cat=1&posts_per_page=5\' ); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> 
<div id="has-tags">
    <ul id="the-tags"><?php the_tags(); ?></ul>
  <?php the_content(); ?>
  <?php endwhile; endif; ?>
</div>
<?php
} else { 
// Whaterver else you\'re doing here.\'
} ?>

结束