Following @TomJNowell advices I descarted the usage of SQL query and aimed at the meta_value sorting. I’ll describe the scenario from the beggining with the solution.
I have a custom taxonomy called “aplication” and another called “segment”, and every application term has a custom field (ACF) for a segment term.
What I needed was to sort the aplication terms by their associated segment term’s name at the edit-tags.php?taxonomy page, but the problem was that the custom field value withhold the ID of the segment term and not it’s name.
So, to workaround this problem, I added another custom field to the aplications, a text field that receives the slug of the segment. This field is automatically updated with the segment’s slug every time that the aplication term is saved.
add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); function update_aplication_segment_name( $term_id, $tt_id, $update ) { $aplication = get_term( $term_id, 'aplication' ); //Gets the object of the current aplication $segment_ID = get_field( 'aplication_segment', $aplication ); //The segment is associated to the aplication through a custom field that returns the segment term's ID $segment = get_term( $segment_ID, 'segment' ); //Gets the segment associated with the current aplication //Remove the hook to avoid loop remove_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); //Updates the value of the 'aplication_segment_name' field of the current aplication update_term_meta( $term_id, 'aplication_segment_name', $segment->slug); //Add the hook back add_action( 'saved_aplication', 'update_aplication_segment_name', 10, 3); }
With the code above, every time that the red field changes, the value of the blue field will change too (the blue field will be hidden from the final user).
Now, to sort the application terms by their segment’s name I adapted the code from this answer: https://wordpress.stackexchange.com/a/277755/218755
add_filter('pre_get_terms', function( $term_query ) { global $current_screen; if ( is_admin() && $current_screen->id == 'edit-aplication' && ( !isset($_GET['orderby']) || $_GET['orderby'] == 'aplication_segment')) { // set orderby to the named clause in the meta_query $term_query -> query_vars['orderby'] = 'order_clause'; $term_query -> query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC"; // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all $args = array('relation' => 'OR', 'order_clause' => array('key' => 'aplication_segment_name', 'type' => 'STRING' ), array('key' => 'aplication_segment_name', 'compare' => 'NOT EXISTS' ) ); $term_query -> meta_query = new WP_Meta_Query( $args ); } return $term_query; });
Now the aplication terms can be sorted by their associated segment term’s name!