我阅读了ACF和;WordPress文档和两者都没有提到在按自定义字段排序分类术语时为什么/何时/如何从数组中删除重复值。
我从中了解到ACF是这样做的StackExchange answer. 但在这个示例代码中,排序不正确,无法与krsort一起使用。对于usort之外的任何内容,它都会给出错误:“krsort()期望参数2很长”。有人能帮忙吗?
我试图用示例代码生成的快捷代码:
function ranker_shortcode( $atts ) {
extract( shortcode_atts(
array(
\'taxonomy\' => \'\',
), $atts
));
$args = array(
\'taxonomy\' => $taxonomy,
);
$sorted = array();
$terms = get_terms( $taxonomy, $args );
if( $terms ) {
foreach ( $terms as $term ) {
$sorted[] = array(
\'height\' => get_field( \'height\', $term ), // Get field from ACF
\'name\' => $term->name,
);
}
krsort( $sorted, SORT_NUMERIC );
foreach( $sorted as $t ) {
$html .= $t[\'height\'] . \', \' . $t[\'name\'] . \'<br>\';
}
return $html;
}
}
add_shortcode( \'ranker\', \'ranker_shortcode\' );
Solved + Answer:多亏了Pieter Goosen,我才得以工作。我对他的答案进行了一些编辑,以包含更多的字段。
/**
* Shortcode to sort taxonomy terms by meta field. Utilizes Advanced Custom Fields plugin.
*/
function sort_term_shortcode( $atts ) {
// Defualt attributes
$attributes = shortcode_atts(
[
\'taxonomy\' => \'\',
], $atts
);
$html = \'\';
$taxonomy = filter_var( $attributes[\'taxonomy\'], FILTER_SANITIZE_STRING );
if ( ! $taxonomy )
return $html; // sanitize shortcode attributes
if ( ! taxonomy_exists( $taxonomy ) )
return $html; // check shortcode attributes exists
$terms = get_terms( $taxonomy );
if( ! $terms )
return $html; // check terms exists
$newterms = [];
foreach ( $terms as $term ) {
$height = get_field( \'height\', $term );
$newterms[$height][] = array(
\'name\' => $term->name,
\'count\' => $term->count,
\'description\' => wpautop( $term->description ),
\'link\' => esc_url( get_term_link( $term ) ),
\'weight\' => get_field( \'weight\', $term )
);
}
krsort( $newterms, SORT_NUMERIC ); // biggest to smallest sort
$c = 0;
foreach( $newterms as $key => $value ) {
foreach ( $value as $v ) {
$c++;
$thumb = wp_get_attachment_image_src( $v[\'avatar\'], \'t_thumb\' );
$html .= \'<div class="panel panel-default">\' . "\\n";
$html .= \'<div class="panel-heading">\' . "\\n";
$html .= \'<h3 class="panel-title">\' . $c . \' <strong>\' . $v[\'name\'] . \'</strong>, \' . $key . \', \' . $v[\'weight\'] . \'lbs.</h3>\' . "\\n";
$html .= \'</div>\' . "\\n";
$html .= \'<div class="media panel-body">\' . "\\n";
$html .= \'<a class="media-left" href="\' . $v[\'link\'] . \'"><img src="\' . $thumb[0] . \'"></a>\' . "\\n";
$html .= \'<div class="media-body">\' . "\\n";
$html .= $v[\'description\'] . "\\n";
$html .= \'</div>\' . "\\n";
$html .= \'</div>\' . "\\n";
$html .= \'</div>\' . "\\n";
}
}
return $html;
}
add_shortcode( \'sort_term\', \'sort_term_shortcode\' );