我正在尝试弄清楚如何使用字母顺序以外的方法在帖子上排列标签。 例如,一篇文章有以下标签; alpha
, beta
, charlie
. 帖子将始终按该顺序组织标签。
我想控制标签在帖子上的显示方式。 而不是按字母顺序排列,我想按照它们被添加到帖子中的顺序来排序帖子标签。 例如; alpha
(进入第2), beta
(进入第一个), charlie
(entered3rd) 将被添加到帖子中,但标签自然会按此顺序列出, alpha, beta, charlie
. 我希望它们按此顺序显示; beta, alpha, charlie
这可能吗? 如果是的话,你能指导我吗?
一种方法是将标签的顺序存储为发布元数据,使用操作 set_object_terms
这恰好按照标签在编辑时出现的顺序传递标签,例如在您的“functions.php”中:
// Called in admin on updating terms - update our order meta.
add_action( 'set_object_terms', function ( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
if ( $taxonomy != 'post_tag' ) {
return;
}
// Save in comma-separated string format - may be useful for MySQL sorting via FIND_IN_SET().
update_post_meta( $object_id, '_tt_ids_order', implode( ',', $tt_ids ) );
}, 10, 6 );
// Reorder terms using our order meta.
function wpse174453_get_the_terms( $terms, $post_id, $taxonomy ) {
if ( $taxonomy != 'post_tag' || ! $terms ) {
return $terms;
}
if ( $ids = get_post_meta( $post_id, '_tt_ids_order', true ) ) {
$ret = $term_idxs = array();
// Map term_ids to term_taxonomy_ids.
foreach ( $terms as $term_id => $term ) {
$term_idxs[$term->term_taxonomy_id] = $term_id;
}
// Order by term_taxonomy_ids order meta data.
foreach ( explode( ',', $ids ) as $id ) {
if ( isset( $term_idxs[$id] ) ) {
$ret[] = $terms[$term_idxs[$id]];
unset($term_idxs[$id]);
}
}
// In case our meta data is lacking.
foreach ( $term_idxs as $term_id ) {
$ret[] = $terms[$term_id];
}
return $ret;
}
return $terms;
}
// Called in front-end via the_tags() or related variations of.
add_filter( 'get_the_terms', 'wpse174453_get_the_terms', 10, 3 );
// Called on admin edit.
add_filter( 'terms_to_edit', function ( $terms_to_edit, $taxonomy ) {
global $post;
if ( ! isset( $post->ID ) || $taxonomy != 'post_tag' || ! $terms_to_edit ) {
return $terms_to_edit;
}
// Ignore passed in term names and use cache just added by terms_to_edit().
if ( $terms = get_object_term_cache( $post->ID, $taxonomy ) ) {
$terms = wpse174453_get_the_terms( $terms, $post->ID, $taxonomy );
$term_names = array();
foreach ( $terms as $term ) {
$term_names[] = $term->name;
}
$terms_to_edit = esc_attr( join( ',', $term_names ) );
}
return $terms_to_edit;
}, 10, 2 );
