0

I see that Wordpress always sorts tags in the Block Editor in the alphabetical order. How can I prevent this behaviour?

I have found a good article with an approach which uses term_order field from the wp_term_relationships DB table

How can I hook into this behaviour in the block editor and change it to correspond to the right order? Any ideas?

wp.state? hooks?

P.S. - there is also a ticket opened on GitHub years ago But it looks like Wordpress devs don't care

1 Answer 1

0

To reorder post tags taxonomy in a non-alphabetical custom order and save it in the Block Editor

To achieve results use a combination of custom code.

// Custom function to fetch tags in custom order
function custom_get_tags($post_id) {
    $tags = get_the_tags($post_id);
    // Modify $tags array to reorder based on custom order
    // Your custom ordering logic here
    return $tags;
}

// Hook into the block editor to modify how tags are displayed
function custom_modify_tag_block($attributes, $content) {
    $post_id = $attributes['postId'];
    $tags = custom_get_tags($post_id);
    // Customize how tags are displayed
    $tag_html = '<div class="custom-tag-container">';
    foreach ($tags as $tag) {
        $tag_html .= '<span class="custom-tag">' . $tag->name . '</span>';
    }
    $tag_html .= '</div>';
    return $tag_html;
}
add_filter('render_block_core/tag-cloud', 'custom_modify_tag_block', 10, 2);

// Hook into saving process to save custom tag order
function custom_save_tag_order($post_id) {
    // Fetch tags associated with the post
    $tags = get_the_tags($post_id);
    // Save custom order metadata for each tag
    foreach ($tags as $tag) {
        // Update metadata for custom order
        update_term_meta($tag->term_id, 'custom_order', $custom_order);
    }
}
add_action('save_post', 'custom_save_tag_order');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.