[Support request] Limit number of tags and categories in post

Home Forums Support [Support request] Limit number of tags and categories in post

Home Forums Support Limit number of tags and categories in post

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #1674143
    Marius

    This is the function from @Tom to move categories and tags above the title of the post.

    add_action( 'generate_before_content', 'tu_add_meta_below_title' );
    function tu_add_meta_below_title() {
    	if ( is_single() ) {
        $categories_list = get_the_category_list( _x( ', ', 'Used between list items, there is a space after the comma.', 'generatepress' ) );
        $categories_list = sprintf( '<span class="cat-links"><span class="screen-reader-text">%1$s </span>%2$s</span>',
            _x( 'Categories', 'Used before category names.', 'generatepress' ),
            $categories_list
        );
    
        $tags_list = get_the_tag_list( '', _x( ', ', 'Used between list items, there is a space after the comma.', 'generatepress' ) );
        $tags_list = sprintf( '<span class="tags-links"><span class="screen-reader-text">%1$s </span>%2$s</span>',
    		esc_html_x( 'Tags', 'Used before tag names.', 'generatepress' ),
    			$tags_list
    	);
    
    	?>
    	<div class="entry-meta">
    		<?php echo $categories_list; ?> | <?php echo $tags_list; ?>
    	</div>
    	<?php
    }
    }

    How can we limit the number of categories to 1 and the number of tags to 2 or 3? Very important, when limiting the number of cats and tags, how can we randomize it? All the functions I found so far are only limiting the number but are showing the tags in alphabetical order meaning on the post you will always see the same tags, which I want to avoid.
    So if I have a post with 10 tags I want to display only 3 at a time, and every time you load that page to display randomly other 3.

    Any suggestion is much appreciated.

    #1674830
    David
    Staff
    Customer Support

    Hi there,

    maybe this function is what you’re looking for:

    https://wordpress.stackexchange.com/a/160130

    #1675217
    Marius

    Hey David,
    Thank you for your reply. I found something and adapted it. Can anyone confirm this code is OK to use and doesn’t create any problems? (I am not a programmer and have no clue what’s happening :P)

    //Tags limit random
    add_filter('term_links-post_tag','limit_to_five_tags');
    function limit_to_five_tags($terms) {
    shuffle($terms);
    return array_slice($terms,0,3,true);
    }
    //Categories limit random
    add_filter('the_category_list','limit_to_one_cat');
    function limit_to_one_cat($terms) {
    shuffle($terms);
    return array_slice($terms,0,1,true);
    }
    
    #1675468
    David
    Staff
    Customer Support

    Looks good to me!

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