自定义分类法在 WooCommerce 中按字母顺序对术语进行分组

问题描述 投票:0回答:1

我对 woocommerce 中的产品有一个品牌分类法。我需要按品牌对产品进行排序。
我感兴趣如何通过代码进行以下操作:

有什么想法吗?

php wordpress woocommerce grouping taxonomy-terms
1个回答
2
投票

要显示按字母顺序分组的链接分类术语,您可以使用以下(在下面的代码中定义正确的自定义分类)

$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,
        '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 ) {
        $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]');
© www.soinside.com 2019 - 2024. All rights reserved.