• Resolved roxchou

    (@roxchou)


    How do I limit the output of categories displayed? I only want to show a few categories that is associated with the current post, on the home page and archive pages only.

    I was able to do this for the homepage with the code below but it didn’t work for the archive:

    // Limit output of categories on home page
    add_filter( 'get_the_categories', function ( $categories )
    {
        global $post;
        // Use $post->ID to target specific posts according to id for your other codition. You will need to implement this yourself
    
        // If this is not the home page or achive page, return $categories as is
        if ( !is_home() || !is_archive() )
            return $categories;
    
        // Return an empty array if we do not have any tags to avoid bugs and unnecessary work
        if ( !$categories )
            return $categories;
    
        // Loop through the tags and count them and break the loop if we reach limit
        $count = 1; // Start our counter
        foreach ( $categories as $category ) {
            if ( $count <= 2 ) { // Set your custom limit here
                $new_category_array[] = $category;
            } else {
                break; // end the foreach loop immediately after the limit is reach, in example, 2
            }
            $count++; // Update the counter
        } // endforeach
    
        return $categories = $new_category_array;
    });

    What am I doing wrong?

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘Limiting the category output’ is closed to new replies.