Sorting custom taxonomy causes menus error

I have a custom taxonomy called knowledgebase, and I’ve modified custom taxonomy to have a ‘category order’ field. So that it can be ordered according to it on a front end.

Now I’ve set it up that I can sort that column (I’ve added that column in the category table). For the sorting I’ve had to add the query using

/**
 * Custom column sortable query
 *
 * @param  array $pieces     Terms query SQL clauses.
 * @param  array $taxonomies An array of taxonomies.
 * @param  array $args     An array of terms query arguments.
 * @return array             Modified query array
 * @since   1.0.0
 */

add_filter( 'terms_clauses', 'mytheme_filter_custom_terms', 10, 3 );

if ( ! function_exists( 'mytheme_filter_custom_terms' ) ) {
    function mytheme_filter_custom_terms( $pieces, $taxonomies, $args ) {

        global $wpdb;

        $orderby = isset( $_REQUEST['orderby'] ) ? trim( wp_unslash( $_REQUEST['orderby'] ) ) : 'cat_order';

        if ( 'cat_order' === $orderby ) {
            $pieces['fields'] .= ', tm.*';
            $pieces['join']   .= ' INNER JOIN '.$wpdb->termmeta.' AS tm ON tt.term_id = tm.term_id';
            $pieces['orderby'] = 'ORDER BY ABS(tm.meta_value)';
        }

        return $pieces ;

    }
}

While this works, it caused the Menus not to work. I didn’t see the Manage Locations, and could not assign the menu to any theme location available in my theme.

Any idea why this happens? Are menus using the terms_clauses hook?

1 Answer
1

Currently your code is modifying all term queries, both in the front-end and in the back-end.

Each navigational menu is registered as a term in the nav_menu taxonomy, so when you visit the backend to work on the menus, those queries have been modified too by your code snippet.

For example, I don’t see any ! is_admin() check in your code.

You should target only the relevant term query, e.g. adding the filter just before the term query and then remove it right again afterwards. Another approach would be to use a custom input argument to activate the filter.

ps: Even though each navigational menu is registered as a term under nav_menu, each menu item is a nav_menu_item custom post type and the tree structure is stored in the post meta table under the _menu_item_menu_item_parent meta key for each post. I just wanted to mention this, as it might be understood from what I wrote here above that the menu is only part of the taxonomy structure.

Leave a Comment