如何获取分配给当前帖子的类别列表?

时间:2011-01-19 作者:Scott B

下面的两个函数用于返回与当前正在查看的帖子类别相同的帖子列表。php

然而,当我var\\u dump on$cat(应该是分配给当前帖子的类别列表)时,我并没有得到我所期望的。在将数组传递到get\\u posts查询之前,是否需要对其进行反序列化?

function get_cats()
{
$post_cats= array();
$categories = get_the_category();
foreach($categories as $cat){
array_push($post_cats, $cat->cat_ID);
}
return $post_cats;
}

//get related posts by category
function ce4_get_related_by_category()
{
global $post;
$cat = implode(\',\',get_cats());
$catHidden=get_cat_ID(\'hidden\');
$myqueryCurrent = new WP_Query();
$myqueryCurrent->query(array(\'cat\' => "$cat,-$catHidden",\'post__not_in\' => get_option(\'sticky_posts\')));
$totalpostcount = $myqueryCurrent->found_posts;
if($totalpostcount > 0)
    {
        echo "<ul>";
        $myposts = get_posts(array(\'cat\' => "$cat,-$catHidden",\'numberposts\' => $cb2_current_count));
        foreach($myposts as $idx=>$post) 
        {
        ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><?php the_excerpt(); ?></li>
        <?php 
        }
        echo "</ul>";
    }
} 

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

你可以用get_the_category()

它将返回属于当前帖子的类别ID数组。


$post_cats= array();
$categories = get_the_category();
foreach($categories as $cat) :
array_push($post_cats, $cat->cat_id);
endforeach;
然后$post\\u cats数组将有一个所有ID的列表。

SO网友:Rarst

您可以像这样单独获取ID数组wp_get_object_terms():

wp_get_object_terms($id, \'category\', array(\'fields\' => \'ids\'))
请注意get_the_category() 缓存结果并从其返回中获取ID实际上可能比单独获取ID更有效。

结束

相关推荐