List a maximum of ‘x’ product categories with qty of ‘y’ in each column

Im trying to list a maximum of ‘x’ product categories with a qty of ‘y’ in each column. ‘x’ will decide how many columns are displayed. If there are less product categories than ‘x’ in the shop then display all. If there are more than ‘x’ then only display full columns ie. multiples of ‘y’, replacing the last entry in the last column with a “view all categories” link.

As an example: With 35 product categories. If max product categories is set to 32, with qty per column set to 8, show 31 product categories in 4 columns and the “view all” link in 32nd place.

The total product categories could be any number. Another example, at the moment I only have 18 categories. If max product categories is set to 16, with qty per column set to 8, show 15 product categories in 2 columns and the “view all” link in 16th place.

I have exhausted my knowledge of if/else logic. Everything i have tried has messed up the results.

Here is the basic code that works to only lists them in columns of 8 up to total of 32, with the link spilling into the next column.

<?php

$args = array(
‘taxonomy’ => ‘product_cat’,
‘orderby’ => ‘name’,
‘number’ => 32, //maximum to list
‘title_li’ => ”,
‘show_count’ => 0, // 1 for yes, 0 for no
‘pad_counts’ => 0, // 1 for yes, 0 for no
‘hierarchical’ => 1, // 1 for yes, 0 for no
‘hide_empty’ => 0, // 1 for yes, 0 for no
‘echo’ => 0, // 1 for yes, 0 for no
‘exclude’ => ’73, 74, 16′, //best sellers, new, and uncategorized
‘depth’ => ‘1’, //top level categories, not sub
‘style’ => ”, //default is list with bullets, ” is without
);

// Grab top level categories
$get_cats = wp_list_categories($args);

// Split into array items
$cat_array = explode(“<br />”,$get_cats);

// Amount of categories (count of items in array)
$results_total = count($cat_array);

// How many tags to show per list-8)
$remainder = ($results_total-8);
$cats_per_list = ($results_total-$remainder);

// Counter number for tagging onto each list
$list_number = 1;

// Set the category result counter to zero
$result_number = 0;
?>

<div class=”cat_columns” id=”cat-col-<?php echo $list_number; ?>”>

<?php
foreach($cat_array as $category) {
$result_number++;

if($result_number >= $cats_per_list) {
$result_number = 0;
$list_number++;
echo ‘<div>’.$category.'</div> </div> <div class=”cat_columns” id=”cat-col-‘.$list_number.'”>’;
}
else {
echo ‘<div>’.$category.'</div>’;
}
}
echo ‘<a href=”https://www.aaaa.com/all-categories//”>View Categories</a>’;
?>

Read more here:: List a maximum of ‘x’ product categories with qty of ‘y’ in each column

Leave a Reply

Your email address will not be published. Required fields are marked *