Display set qty of product categories in columns with a link to surplus

Im trying to list product categories up to a certain qty (x) in a dropdown menu, but if the total amount of product categories in the shop are greater than x then only list x minus 1 and display “view all categories” link in last place.

As an example: With 35 product categories. If max product categories is set to 32, with max 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 max per column set to 8, show 15 product categories in 2 columns and the “view all” link in 16th place.

Im a beginner and 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:: Display set qty of product categories in columns with a link to surplus

Leave a Reply

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