Support » Developing with WordPress » How to limit tag count

  • Resolved wyclef

    (@wyclef)


    Hi, trying to limit tag count to 5. With no limit,

    this works:

    function pastLectures() {
        $args = array('order' => 'DESC');
        $posttags = get_tags($args);
        $tags = '';
        $tags .= '<ul>';
        if ($posttags) {
            foreach($posttags as $tag) {
                $tempYear = substr($tag->slug, 0, 4);
                $pastLecturesYes = get_field('add-to-past-lecture-series', 'post_tag_'.$tag->term_id);
                if ($pastLecturesYes[0] == 'add') {
                    $tagLink = get_tag_link($tag->term_id);
                    $tags .= '<li><a href="'.$tagLink.'"> '.$tag->name.'</a></li>';
                }
            }
        }
        $tags .= '</ul>';
        return $tags;
    }

    trying to limit count to 5 isn’t working, what am I doing wrong?

    
    function pastLectures() {
        $args = array('order' => 'DESC');
        $posttags = get_tags($args);
        $count = 0;
        $tags = '';
        $tags .= '<ul>';
        if ($posttags) {
            foreach($posttags as $tag) {
                $count++;
                $tempYear = substr($tag->slug, 0, 4);
                $pastLecturesYes = get_field('add-to-past-lecture-series', 'post_tag_'.$tag->term_id);
                if ($pastLecturesYes[0] == 'add') {
                    $tagLink = get_tag_link($tag->term_id);
                    $tags .= '<li><a href="'.$tagLink.'"> '.$tag->name.'</a></li>';
                }
                if( $count >5 ) break;
            }
        }
        $tags .= '</ul>';
        return $tags;
    }
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator t-p

    (@t-p)

    Thread Starter wyclef

    (@wyclef)

    Trying to just limit the count to 5 on the working chunk of code. Thinking I am just missing something simple here.

    Thread Starter wyclef

    (@wyclef)

    Never mind, just had the count and count++ mixed up here is the working code.

    function pastLectures() {
        $args = array('order' => 'DESC');
        $posttags = get_tags($args);
        $count = 0;
        $tags = '';
        $tags .= '<ul>';
        if ($posttags) {
            foreach($posttags as $tag) {
                //print_r($tag);
                $tempYear = substr($tag->slug, 0, 4);
                $pastLecturesYes = get_field('add-to-past-lecture-series', 'post_tag_'.$tag->term_id);
                if ($pastLecturesYes[0] == 'add') {
                    $count++;
                    $tagLink = get_tag_link($tag->term_id);
                    $tags .= '<li><a href="'.$tagLink.'"> '.$tag->name.'</a></li>';
                    if( $count > 4 ) break;
                }
    
            }
        }
        $tags .= '</ul>';
        return $tags;
    }
    Moderator t-p

    (@t-p)

    Glad its sorted 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.