Limit amounts of categories in wordpress

Asked

Viewed 103 times

1

Hello, all right.

I have a question here and I’d like a little help from you

I have the following code:

<?php $prod_marca = get_field('categoria_e_tags_marca');
        if( $prod_marca ): ?>
        <ul>
            <li><b>Marca</b></li>
            <?php foreach( $prod_marca as $term ): ?>
              <li class="text-small-lista"><?php echo $term->name; ?></li>
            <?php endforeach; ?>
        </ul>
        <?php endif; ?>

In this code I pull a field of Advanced Custom Field that returns me several categories, but I don’t want to print all categories, I want to limit the number of categories that will be printed.

Today the layout breaks because it appears in a block 5 categories and in another block 20 categories.

I wanted to limit to 5 categories only, IE, no matter how many categories are set in admin, will only print 5.

Will I be able to make clear the help I need?

Thanks in advance to all who can help me with this doubt.

Att...

  • A friend passed me the following information that solved my problem <?php foreach( array_slice($prod_marca, 0, 5) as $term ): ?>

1 answer

1


Use the array_slice to extract a portion of an array, in the following example, you will go through the array at position 0 until you reach position 5

foreach( array_slice($prod_marca, 0, 5) as $term ): ?>
     <li class="text-small-lista"><?php echo $term->name; ?></li>
<?php endforeach ?>

Tip: If you are creating categories of posts and/or custom posts, the correct is to work with taxynomy in wordpress and not create a custom field to simulate a category in the post.

Documentation teaching how to create a taxynomy: https://codex.wordpress.org/Function_Reference/register_taxonomy

Tutorial Basic step by step how to create a taxynomy in a custom post: https://blog.mxcursos.com/taxonomia-no-wordpress/

  • 1

    Thank you Glaydson for the answer... it worked correctly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.