我试图在每一列中列出最大的“x”产品类别(y的倍数),其数量为‘y’。‘x’决定显示了多少列。
我想做的是:-如果商店里的产品种类比‘x’少,那么就全部展示。-如果有“x”,则显示“x”。-如果有超过‘x’显示x-1,并显示一个“查看所有类别”链接在最后一个位置。
作为一个例子:有35个产品类别。如果最大的产品categories=32和每个column=8的数量,在4列中显示31个产品类别,在第32位显示“查看所有”链接。
总产品类别不断变化,所以我试图使代码动态工作在任何数量,而不需要改变代码,除非改变'x‘或'y’。
下面是我能够为我工作的基本代码,但是链接溢出到下一列,而不是前一列的最后一位。作为初学者,我已经用尽了if/else逻辑的知识,而我尝试过的其他一切都在破坏输出。
'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("
",$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;
?>
= $cats_per_list) {
$result_number = 0;
$list_number++;
echo ''.$category.' ';
}
else {
echo ''.$category.'';
}
}
echo 'View Categories';
?> 发布于 2019-09-11 00:43:34
因此,这与您的代码(以及被接受的另一个问题的答案中的代码)不同,但对我来说效果很好:
您可以删除我添加的"\t" .和. "\n",以便更好地检查生成的HTML。如果你对代码的任何部分有任何疑问请告诉我。:)
// First, define these.
$max_cat_count = 32; // this is 'x'
$qty_per_column = 8; // this is 'y'
// Then the $args array.
$args = array(
'taxonomy' => 'product_cat',
'number' => $max_cat_count + 1, // keep the + 1
'title_li' => '',
'hide_empty' => 0,
'echo' => 0,
'style' => '',
// ... your other args here ...
);
// Get the categories list.
$get_cats = wp_list_categories( $args );
// Split the list into array items.
$cat_array = explode( "
", $get_cats );
$total = count( $cat_array );
$list_number = 1;
$_new_col = false;
foreach ( $cat_array as $i => $category ) {
if ( $i >= $max_cat_count ) {
break;
}
if ( $i % $qty_per_column === 0 ) {
// Close previous column, if any.
if ( $_new_col ) {
echo '' . "\n";
}
// Open new column.
$id = 'cat-col-' . $list_number;
echo '' . "\n";
$_new_col = true;
$list_number++; // increment the columns count
}
if ( $total > $max_cat_count && $i === $max_cat_count - 1 ) {
// Make sure to change the # to the proper URL.
echo "\t" . 'View All' . "\n";
} else {
echo "\t" . '' . trim( $category ) . '' . "\n";
}
}
// Close last column, if any.
if ( $_new_col ) {
echo '' . "\n";
}https://wordpress.stackexchange.com/questions/346867
复制相似问题