1

我有一个php代码,如下所示:

$category = get_the_category();//线#A

echo '<pre>'; print_r($category); echo '</pre>';// 添加#B行用于调试目的

Line#A 处的代码检索帖子类别。

我为调试目的添加的第二行代码返回以下数组;

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 13085
            [name] => Cannabis
            [slug] => democracy_project_cannabis
            [term_group] => 0
            [term_taxonomy_id] => 13085
            [taxonomy] => category
            [description] => Hello World 
            [parent] => 13083
            [count] => 8
            [filter] => raw
            [cat_ID] => 13085
            [category_count] => 8
            [category_description] => Good Morning
            [cat_name] => Cannabis
            [category_nicename] => democracy_project_cannabis
            [category_parent] => 13083
        )

    [1] => WP_Term Object
        (
            [term_id] => 13093
            [name] => Today
            [slug] => today
            [term_group] => 0
            [term_taxonomy_id] => 13093
            [taxonomy] => category
            [description] => 
            [parent] => 0
            [count] => 3
            [filter] => raw
            [cat_ID] => 13093
            [category_count] => 3
            [category_description] => 
            [cat_name] => Today
            [category_nicename] => today
            [category_parent] => 0
        )

)

问题陈述:

我想知道我需要在 Line#A 之后添加什么 php 代码,以便它只需要类别 [name] => Today。

Line#A 处的代码返回特定帖子的类别列表。我只想拿一个类别。

我想我需要使用 array_filter() 方法,但我不确定如何使用它。

4

2 回答 2

1

我认为你最好从一个特定的类别开始获取你想要的帖子,而不是过滤所有内容。

$term = get_term_by('name', 'Today', 'category');
if ($term) {
  $category = get_the_category($term->term_id);
} else {
  echo "Category not found";
}
于 2019-03-20T20:57:24.470 回答
0

您可以遍历返回的$category数组:

foreach($category as $cat) {

    if ($cat->name == 'Today') {
        //do your stuff
    }

}
于 2019-03-20T20:51:27.050 回答