如何排除特定类别并仅显示get_the_category()中的一个;

时间:2017-07-31 13:21:04

标签: wordpress

例如我有一个类别的帖子:cat1,cat2,cat3,我想排除cat1并只显示cat2或cat3中的一个。

 <?php
   $categories = get_the_category();
   $separator = ' ';
   $output = '';
         if($categories){
         foreach($categories as $category) {
         if($category->name !== 'Cat1'){
         $output .= $category->cat_name;}
         }
         echo trim($output, $separator);
         }
 ?>

我试过这个循环,但它只适用于排除&#34; Cat1&#34;我还想从get_the_category()中显示一个类别; ?

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

像这样的东西

foreach($categories as $category) {
     if($category->name !== 'Cat1'){
     $output = $category->cat_name;
    if($output != '') break; //end foreach when we have value
}

答案 1 :(得分:0)

使用&#34;排除&#34;排除类别在wordpress中用逗号分隔值类别id的参数

<?php
    $cat_args = array(
        'type'          => 'post',
        'parent'        => 0,
        'orderby'       => 'name',
        'order'         => 'ASC',
        'hide_empty'    => 0,
        'hierarchical'  => true,
        'exclude'       => '1,2,3',
        'include'       => '',
        'number'        => '',
        'taxonomy'      => 'category',
        'pad_counts'    => true 

    ); 
    $categories  = get_categories( $cat_args );
    if(count($categories )>0)
    {

       $separator = ' ';
       $output = '';
       foreach ( $categories  as $category ) {

             $output .= $category->cat_name;
             echo trim($output, $separator);
        }
    }
    ?>