1

I have this code to show cathegory like image:

<?php 
foreach((get_the_category()) as $cat)
{
    $catname =$cat->category_nicename;
    echo "<a href=\"/category/";
    echo $catname;
    echo "/\">";
    echo "<img src=\"/wp-content/categorias/";
    echo $catname;
    echo ".png\" alt=\"$catname category image\" /></a>\n";
}
?>

The problem is: I want to show only one category by post because I have a lot of posts with more than one category. I want to show only one category.

2

CHRISTMAS EDITION

Due to Christmas time and my brain hitting some serious technical difficulties, I got get_the_category() and get_the_categories filter mixed up.

Here is the revised filter function, working:

You can also make use of the get_the_categories filter

add_filter( 'get_the_categories', function ( $categories )
{
    // Only return the first object in the array
    return $cat[] = $categories[0];
}); 

ORIGINAL ANSWER

Because you pass everything directly to your foreach loop, the easiest ist to break the loop after the first iteration

<?php 
foreach((get_the_category()) as $cat)
{
    $catname =$cat->category_nicename;
    echo "<a href=\"/category/";
    echo $catname;
    echo "/\">";
    echo "<img src=\"/wp-content/categorias/";
    echo $catname;
    echo ".png\" alt=\"$catname category image\" /></a>\n";

    // Lets break the loop after one iteration
    break;
}
?>
  • You don't even need that if, just break at the end of the loop ;) – TheDeadMedic Dec 22 '15 at 13:14
  • @TheDeadMedic ya, thanks for that reminder. Seems I was trying to get to clever again here ;-) – Pieter Goosen Dec 22 '15 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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