Display WooCommerce product categories in a 4 columns custom menu [closed]

The following will display in 4 columns 32 terms max at all (product categories) so 8 items by column. If there is more than 32 terms, it replace the 32th term by “View Categories” custom linked item:

<?php

## Settings
$items_per_col  = 8; // Number of items by column
$number_of_cols = 4; // Number of columns
$taxonomy       = 'product_cat'; // WooCommerce product category taxonomy
$excluded_ids="73, 74, 16"; // Excluding "best sellers", "New" and "Uncategorized" terms Ids

## Initializing variables
$col_count = 1;
$counter   = 0; 
$html="";

$max_items = $number_of_cols * $items_per_col; // Max number of items (calculation)

$terms_list = wp_list_categories( array(
    'taxonomy'     => $taxonomy,
    'number'       => ( $max_items + 1 ), // 33 max
    'title_li'     => '',  // disabled
    'pad_counts'   => 0,   // no
    'hide_empty'   => 0,   // no
    'echo'         => 0,   // return (not echo)
    'style'        => '',  // Without style (bullets)
    'depth'        => '1', // Top level terms only
    'exclude'      => $excluded_ids,
) );

$terms_array = explode( "<br />", $terms_list ); // Split each item in an array of terms

array_pop($terms_array); // <== We remove last empty item from the array.

$items_count = count($terms_array); // get items (terms) count

// Loop through product categories terms
foreach ( $terms_array as $term_html ) {
    if ( $counter == 0 ) { // column start
        $html .= '<div class="cat-columns" id="cat-col-' . $col_count . '" style="float:left; margin: 0 10px;">';
    }

    if( $items_count > $max_items && $col_count == $number_of_cols && $counter == ($items_per_col - 1) ) {
        $link    = home_url( "/all-categories/", "https" );
        $html .= '<div><a href="' . $link . '">' . __("View Categories") . '</a></div>';
    }
    else {
        $html .= '<div data-counter="'.$counter.'">' . $term_html . '</div>';
    }

    $counter++; // Increase items counter

    if ( $counter == $items_per_col ) { // column end
        $html .= '</div>';

        $counter = 0; // Reset items counter
        $col_count++; // Increase colum count

        if ( $col_count > $number_of_cols ) {
            break; // Stop the loop (to be sure)
        }
    }
}

## html output
echo '<div class="categories-wrapper">' . $html. '</div>'; 
?>

Tested and works.

Leave a Comment