循环内容 - 单

时间:2016-01-07 09:45:21

标签: php wordpress

我尝试为用户构建一个选项,以突出显示"相关帖子"要显示在单个帖子的底部,所以我将此代码放在" content-single.php"的底部:

<div class="related-post">

    <?php 

        $args = array(  'post__in'      => array(38328, 38359, 21321) );//it's going to be the user choice, for example, I put three id's

        $related_query = new WP_Query($args);
        if ($related_query): 
         echo '<div class="row">';
         while ($related_query->have_posts()): $related_query->the_post();?>

             <div class="col-sm-4">
                 <?php
                 if (has_post_thumbnail()):
                     the_post_thumbnail();
                 endif;
                 ?>
                 <?php the_title() . '<br/>'; ?>
             </div>
         <?php endwhile;
         echo '</div>';
         wp_reset_postdata();       
     ?>


</div>

但在某些帖子中,我收到了8个不同的帖子,在某些帖子中我没有收到任何帖子(虽然我只在帖子中放了三个id)。 我想问题是我尝试在主循环内循环。 我尝试使用query_posts并使用get_posts,但无法正常工作。

任何帮助都将不胜感激!

3 个答案:

答案 0 :(得分:0)

我认为这与缺少的post_type参数有关。但是你需要在循环结构中进行一些修正:

<div class="related-post">
<?php
    $args = array( 'post_type' => 'your_post_type', 'post__in' => array(38328, 38359, 21321) );
    $related_query = new WP_Query($args);
    if( $related_query->have_posts() ){ ?> 
    <div class="row"><?php
        while( $related_query->have_posts() ){ $related_query->the_post();?>
            <div class="col-sm-4"><?php
                if( has_post_thumbnail() ) the_post_thumbnail();
                the_title();?>
            </div><?php
        }
        wp_reset_postdata();?>
    </div><?php
    }?>
</div>

<强>更新

请尝试将'posts_per_page' => 3添加到args阵列。

答案 1 :(得分:0)

我有这个帖子的解决方案。希望你的查询帖子错了。

<div class="related-post">
<?php
$args = array( 
    'post_type' => 'your_post_type', 
    'post__in' => array(38328, 38359, 21321),
    'post_status'=>'publish'
    );
$related_query = new WP_Query( $args );
?>
<?php if ( $related_query->have_posts() ) : ?>
    <div class="row">
    <?php while ( $related_query->have_posts() ) : $related_query->the_post(); ?> 
    <div class="col-sm-4">   
    <!-- do stuff ... -->
    the_post_thumbnail();
    the_title();
    </div>
    <?php endwhile; ?>
    </div>
<?php endif;  wp_reset_postdata(); ?>
</div>  

希望这样可以帮助您获取所需的输出。 确保您在post_in部分中提到的ID中发布了帖子。

答案 2 :(得分:0)

好吧,我设法通过在参数中添加'ignore_sticky_posts' => 1来解决这个问题。谢谢@Pieter Goosen

相关问题