如何解决在 WooCommerce 中按字母顺序对术语进行自定义分类
我有一个 woocommerce 产品的品牌分类法。我需要按品牌对产品进行分类。
我对如何通过代码进行以下操作很感兴趣:
有什么想法吗?
解决方法
要显示按字母顺序分组的链接分类术语,您可以使用以下(在下面的代码中定义正确的自定义分类):
$taxonomy = 'product_brand'; // <== Here define your custom taxonomy
$sorted = array(); // Initializing
// Get all terms alphabetically sorted
$terms = get_terms( array(
'taxonomy' => $taxonomy,'hide_empty' => true,'orderby' => 'name'
) );
// Loop through the array of WP_Term Objects
foreach( $terms as $term ) {
$term_name = $term->name;
$term_link = get_term_link( $term,$taxonomy );
$first_letter = strtoupper($term_name[0]);
// Group terms by their first starting letter
if( ! empty($term_link) ) {
$sorted[$first_letter][] = '<li><a href="'.$term_link.'">'.$term_name.'</a></li>';
} else {
$sorted[$first_letter][] = '<li>'.$term_name.'</li>';
}
}
// Loop through grouped terms by letter to display them by letter
foreach( $sorted as $letter => $values ) {
echo '<div class="tax-by-letter">
<h3 class="tax-letter-'.$letter.'">'.$letter.'</h3>
<ul>' . implode('',$values) . '</ul>
</div>';
}
它适用于任何分类法或自定义分类法(更适合非层次分类法)。
现在可以将其嵌入到简码中以便于使用:
add_shortcode( 'terms_by_letter','display_terms_by_letter' );
function display_terms_by_letter( $atts ) {
// Shortcode Attributes
extract( shortcode_atts( array(
'taxonomy' => 'product_brand',// <== Here define your taxonomy
),$atts,'terms_by_letter' ) );
$sorted = array(); // Initializing
$output = ''; // Initializing
// Get all terms alphabetically sorted
$terms = get_terms( array(
'taxonomy' => $taxonomy,'orderby' => 'name'
) );
// Loop through the array of WP_Term Objects
foreach( $terms as $term ) {
$term_name = $term->name;
$term_link = get_term_link( $term,$taxonomy );
$first_letter = strtoupper($term_name[0]);
// Group terms by their first starting letter
if( ! empty($term_link) ) {
$sorted[$first_letter][] = '<li><a href="'.$term_link.'">'.$term_name.'</a></li>';
} else {
$sorted[$first_letter][] = '<li>'.$term_name.'</li>';
}
}
// Loop through grouped terms by letter to display them by letter
foreach( $sorted as $letter => $values ) {
$output .= '<div class="tax-by-letter">
<h3 class="tax-letter-'.$letter.'">'.$letter.'</h3>
<ul>' . implode('',$values) . '</ul>
</div>';
}
return $output;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。
简码用法:
[terms_by_letter]
或在 PHP 代码中:
echo do_shortcode('[terms_by_letter]');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。