【发布时间】:2021-04-24 10:33:27
【问题描述】:
我修改了一个我发现的函数来做我需要的,虽然它可以工作,但不幸的是返回的结果没有任何特定的顺序,我需要它们按字母顺序排列。
此脚本返回来自 Woocommerce 的子类别列表:
function get_product_subcategories_list( $category_slug ){
$terms_html = array();
$taxonomy = 'product_cat';
// Get the product category (parent) WP_Term object
$parent = get_term_by( 'slug', $category_slug, $taxonomy );
// Get an array of the subcategories IDs (children IDs)
$children_ids = get_term_children( $parent->term_id, $taxonomy );
// Loop through each children IDs
foreach($children_ids as $children_id) {
$term = get_term( $children_id, $taxonomy ); // WP_Term object
$term_link = get_term_link( $term, $taxonomy ); // The term link
$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
if ( is_wp_error( $term_link ) ) $term_link = '';
// Set in an array the html formatted subcategory name/link
$terms_html[] = '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</li></a>';
}
return '<ul>' . implode( $terms_html ) . '</ul>';
}
...这并不重要,但这在我的模板中:
get_product_subcategories_list( $post->post_name );
问题是$terms_html[] 正在返回这个...
<li><a href="https://example.com/pants">Pants</a></li>
<li><a href="https://example.com/shoes">Shoes</a></li>
<li><a href="https://example.com/hats">Hats</a></li>
...但我需要它像这样按字母顺序排列:
<li><a href="https://example.com/hats">Hats</a></li>
<li><a href="https://example.com/pants">Pants</a></li>
<li><a href="https://example.com/shoes">Shoes</a></li>
【问题讨论】:
-
只使用
sort():3v4l.org/UZX2q
标签: php wordpress sorting woocommerce foreach