如何在single.php上显示此single.php所在的所有类别的帖子

时间:2014-04-01 11:23:10

标签: php wordpress

例如,我有一些包含五个帖子的类别。当我选择帖子时,需要显示其所在类别的其余四个帖子。

<?php
$infocat = get_the_category();
$info = $infocat[0]->cat_ID;
$array = "orderby=rand&showposts=10&cat=$info";
query_posts($array);    
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<a class="permlinccat" href="<?php the_permalink() ?>" title="Перейти к посту: <?php    the_title(); ?>" ><?php the_title(); ?></a>
<?php endwhile; else: ?>
<?php endif; wp_reset_query(); ?>

试过这个功能 - 几乎不错,但它只获得帖子的标题

找到了解决方案......

<?php
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category-  >term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=>5 // 
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
echo '<h3>Current category</h3><ul>';
while ($my_query->have_posts()) {
$my_query->the_post();
?>
<a href="<?php the_permalink() ?>" rel="bookmark" title=" <?php the_title_attribute(); ? >"><?php the_title(); ?>
<img src="<?php echo first_image() ?>"title="<?php the_title(); ?>" alt="<?php  the_title(); ?>"/>
</a>
<?php
}
echo '</ul>';
}
}
?>

1 个答案:

答案 0 :(得分:0)

试试这个:)只需获取当前类别并从查询中排除当前帖子。

<?php
    $cat = get_the_category();
    $catOK = $cat[0]->cat_ID; //if multiple categories
    $postID = $post->ID;
    query_posts(
        array(
            'cat' => $catOK,
            'post__not_in' => array($postID)
            )
        );
    while (have_posts()) : the_post(); ?>

    YOUR HTML CODE

    <?php endwhile; ?>