对标签进行排序,但不按字母顺序

时间:2015-01-10 作者:Mr. B

我正在试图找出如何在帖子上使用除字母顺序以外的其他方法排列标签。例如,一篇文章有以下标签:;alpha, beta, charlie. 帖子将始终按照该顺序组织标签。

我想控制标签在帖子上的显示方式。我不想按字母顺序排列,而是想按标签添加到帖子中的顺序排列。例如alpha (第2个输入),beta (输入1),charlie(entered3rd)将添加到帖子中,但标签自然会按此顺序列出,alpha, beta, charlie. 我希望它们按此顺序显示;beta, alpha, charlie

这可能吗?如果是的话,你能告诉我吗?

1 个回复
SO网友:bonger

一种方法是使用操作将标记的顺序存储为post元数据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 );

结束

相关推荐

Custom Admin Menu Order

我的函数中有一个简单的解决方案。php用于重新排序管理菜单。这是:// Admin menu - reorder function custom_menu_order($menu_ord){ if (!$menu_ord) return true; return array( \'index.php\', // Dashboard \'edit.php?post_type=page\', // Pages \'edit.php