0

I am trying to limit the amount of category tags I output to 5 as well as append a "..." to the end of any items where the output was limited. I've got it mostly working except I can't figure out how to only echo the first 5 tags.

I should mention I only want this to take place on a particular page, but the code I am working with is stored in the functions file but is called by the page in question.

The ideal output would look like this:

Item 1: tag 1, tag 2, tag 3

Item 2: tag 1, tag 2, tag 3, tag 4, tag 5...

This is the code I have so far. I think I need to use array_splice but am not sure how to implement it.

if ( $type === 'portfolio' ) {
            $terms = get_the_term_list( $post->ID, 'royal_portfolio_cats', '', $separator );
            $term_array = explode(',',$terms);
            $count = sizeof($term_array);               
            if ($count <= 5) {
                echo $terms;
            }
            elseif ($count > 5) {

                $limit_terms = //Do something to output only the first 5 terms with comma separators

                echo $limit_terms."...";
            }
        }
4
  • 1
    Try this if ( $limit = array_slice($term_array, 0, $max = 5) ) { echo implode( ", ", $limit ); if ( count( $terms ) > $max ) { echo " ..."; } } after $term_array
    – Ismail
    Jun 16, 2016 at 0:14
  • That worked! Except I had to use $term_array instead of if ( count( $terms ) > $max ) { echo " ..."; }
    – Heather
    Jun 16, 2016 at 0:29
  • 1
    Oops. Forgot that one ;)
    – Ismail
    Jun 16, 2016 at 0:39
  • 1
    You could also filter on term_links-royal_portfolio_cats which passes an array to it - but it doesn't pass args so you don't have access to before or after in order to add the ellipsis.
    – Howdy_McGee
    Jun 16, 2016 at 0:58

1 Answer 1

2

Samuel Elh correctly answered this.

    if ( $type === 'portfolio' ) {
            $terms = get_the_term_list( $post->ID, 'royal_portfolio_cats', '', $separator );
            $term_array = explode(',',$terms);

            if ( $limit = array_slice($term_array, 0, $max = 5) ) { 
                echo implode( ", ", $limit ); 
                if ( count( $term_array ) > $max ) { 
                    echo "..."; 
                } 
            };

        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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