Setting maximum number of results in product category array

This code displays a list of images/links to products according to the category. Works great, but showing way too many results. Wondering if I can limit it to show just maximum of 8 at random?

Currently:

<?php

$prod_categories = get_terms( 'product_cat', array(
    'orderby'    => 'name',
    'order'      => 'DSC',
    //'include'         => '39, 38, 37, 28, 26, 40',
    'exclude'           => '32, 38',
    'hide_empty' => 1
));

foreach( $prod_categories as $prod_cat ) :
    $cat_thumb_id = get_woocommerce_term_meta( $prod_cat->term_id, 'thumbnail_id', true );
    //$cat_thumb_url = wp_get_attachment_thumb_url( 'Full Size', $cat_thumb_id );
    $cat_thumb_url = wp_get_attachment_url($cat_thumb_id, $size = 'full');
    $term_link = get_term_link( $prod_cat, 'product_cat' );

?>

Related posts

1 comment

  1. Per the WordPress get_terms() documentation you can use the number argument:

    Limiting the number of terms

    $prod_categories = get_terms( 'product_cat', array(
        'orderby'    => 'name',
        'order'      => 'DSC',
        //'include'  => '39, 38, 37, 28, 26, 40',
        'exclude'    => '32, 38',
        'hide_empty' => 1,
        'number'     => 8
    ));
    

    Include / Exclude should be arrays

    Also, as a side-note, your include / exclude parameters are incorrect – they should be arrays:

    $prod_categories = get_terms( 'product_cat', array(
        'orderby'    => 'name',
        'order'      => 'DSC',
        //'include'  => array(39, 38, 37, 28, 26, 40),
        'exclude'    => array(32, 38),
        'hide_empty' => 1,
        'number'     => 8
    ));
    

    Random Terms?

    And lastly, you mention random. get_terms does not support random order, so that would need to be done in PHP. In order to do so, we’d want to remove the number limit, and then process the results in PHP, like so:

    $prod_categories = get_terms( 'product_cat', array(
        'orderby'    => 'name',
        'order'      => 'DSC',
        //'include'  => '39, 38, 37, 28, 26, 40',
        'exclude'    => '32, 38',
        'hide_empty' => 1
    ));
    
    // Randomize
    $prod_categories = shuffle($prod_categories);
    
    // Limit to 8
    $prod_categories = array_slice($prod_categories, 0, 8);
    
    // Now do your foreach loop...
    

Comments are closed.