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

Custom taxonomy grouped terms by letter alphabetically in 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,
        '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]');