【问题标题】:array to exclude specific categories from showing as FIRST category using get_the_category()使用 get_the_category() 排除特定类别显示为第一个类别的数组
【发布时间】:2016-09-06 20:15:53
【问题描述】:

我正在使用此代码在我的页面模板上仅显示帖子的第一个类别,但我需要找到一种方法从中排除某些特定类别

$category = get_the_category(); echo $category[0]->cat_name;?

例子:

假设我有一篇关于树类别的帖子:“admin cat”“admin cat2”“item cat”。如果我使用这个函数,输出将是:

这篇文章在“admin cat”下!

我需要它是:

这篇文章在“item cat”下!

是否可以在我的代码的输出中添加一组将在输出中省略的猫,或者我应该使用其他方法吗?

【问题讨论】:

  • 您是否总是希望类别结束它可能是随机的??
  • @sismaster 你能解释一下你的问题吗?

标签: php wordpress function


【解决方案1】:

试试这个:https://wordpress.org/support/topic/exclude-categories-from-the_category/

<?php the_excluded_category(array(1,328,338,339)); ?>
function the_excluded_category($excludedcats = array()){
$count = 0;
$categories = get_the_category();
foreach($categories as $category) {
    $count++;
    if ( !in_array($category->cat_ID, $excludedcats) ) {
        echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "Cortos de %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';

        if( $count != count($categories) ){
            echo ", ";
        }

    }
}

}

【讨论】:

  • 这意味着只输出一个类别
【解决方案2】:

只需遍历您的类别数组,并将每个项目与排除的类别数组进行匹配。这将返回第一个不匹配的类别。

function getCategory() {
    $categories = array('admin cat','admin cat2', 'item cat', 'some other cat', 'dog');
    $excluded_categories = array('admin cat','admin cat2');

    foreach($categories as $category) {
        if (!in_array($category,$excluded_categories)) {
            return $category;
        }
    }

    return false;
}

echo getCategory();
// outputs 'item cat'

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    相关资源
    最近更新 更多