Mateo
Mateo

Reputation: 1

How to exclude specific category and show only one from the get_the_category();

For example i have a post in category: cat1,cat2,cat3 and i want to exclude cat1 and show only one from cat2 or 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);
         }
 ?>

I have tried this loop but it only works for excluding "Cat1" i also want to show one category from get_the_category(); ?

Can someone help me?

Upvotes: 0

Views: 3210

Answers (2)

Shital Marakana
Shital Marakana

Reputation: 2887

exclude category by using "exclude" argument with comma separated value category id in wordpress

<?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);
        }
    }
    ?>

Upvotes: 1

Muhammad Asad
Muhammad Asad

Reputation: 3793

Something like this

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

Upvotes: 0

Related Questions