Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How can I get the first category (linked to the category archive page) of a post excluding the category called 'featured'? I found various solutions but I can't combine them properly.

Thanks

UPDATE:

This is what I ended up using:

$category = get_the_category(); 
$cat_id = get_cat_ID( $name );
$link = get_category_link( $cat_id );

if($category[0]->cat_name == "featured") {
     echo '<a href="'. esc_url( $link ) .'"">'. $category[1]->cat_name .'</a>';
} else {
     echo '<a href="'. esc_url( $link ) .'"">'. $category[0]->cat_name .'</a>';
}
share|improve this question
    
One thing to consider is that there isn't really a logical 'first' category to a post, in the sense of one being the "primary" or "most important" or even "first assigned" category. –  s_ha_dum Feb 6 '13 at 15:10
    
So what category does wordpress take as first? Random? Btw I needed this to use this on a slider caption, and I don't want more then one category listed there. I'll display the full categories list at the end of each post. Thanks for the observation, but why the downvote?? –  djwd Feb 6 '13 at 15:17
    
Which one is first in the return set depends on the query that pulls the categories. For example, get_categories defaults to sorting by ID, which would mean sorting by category creation order. That can be changed to sort by other fields, like "name". You can also reverse the return set. –  s_ha_dum Feb 6 '13 at 15:26

1 Answer 1

up vote 0 down vote accepted

Within the post loop you can do,

$category = get_the_category(); 

if($category[0]->cat_name == "featured") {

    //if first category in array is "featured", get next category in line

     $name = $category[1]->cat_name;
     $cat_id = get_cat_ID( $name );
     $link = get_category_link( $cat_id );
     echo '<a href="'. esc_url( $link ) .'"">'. $name .'</a>';

} else {

    //get the first category

     $name = $category[0]->cat_name;
     $cat_id = get_cat_ID( $name );
     $link = get_category_link( $cat_id );
     echo '<a href="'. esc_url( $link ) .'"">'. $name .'</a>';

}

If you are outside the loop you can pass a post ID to get_the_category($id);

Note: Its crude... you could simplify this logic.

Edit: Here is a link to an answer that provides a more refined approach using the array_pop which you could adapt to your situation:

Get the first Category / Term only in single-custom-post.php

share|improve this answer
    
Thank you I got what I was missing, it works I only didn't understand why you doubled all the variables. I'll update my question with a shorter version. Thank you very much indeed. –  djwd Feb 6 '13 at 15:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.