I'm trying to list a set amount of product categories (x) in a dropdown menu, but if the total amount of product categories are greater than x then only list x minus 1 and display “view all categories” link in last place. What I'm trying to achieve is only 8 entries per column (including view all link) with 4 columns total.
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 lists them in columns of 8 up to total of 32. Id like if there are 33 or more categories for the 32nd to be a link to all of them. If only 32 then just list all 32 with no link.
<?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>';
?>