Answer the question
In order to leave comments, you need to log in
Sorting taxonomy terms by meta field value in WordPress?
There is a task in WordPress for custom taxonomy to display terms sorted by the value of the meta field in DATETIME (Ymd H: i: s) format, the
meta field is set using the ACF plugin and everything is ok in the database:
full code:
add_filter( 'get_terms_args', function ( $args, $taxonomies ) {
global $pagenow;
if ( is_admin() && $pagenow == 'edit-tags.php' && $taxonomies[0] == 'program_session' ) {
$args['meta_query'] = [
'relation' => 'AND',
'conference' => [
'key' => 'conference_id',
'value' => get_active_conf_id(),
'compare' => 'LIKE'
],
'session_start' => array(
'key' => 'program_session_start',
'type' => 'DATETIME',
'compare' => 'EXISTS',
),
];
$args['orderby'] = 'session_start';
$args['order'] = 'ASC';
}
return $args;
}, 10, 2 );
$term_query = new WP_Term_Query( [
'taxonomy' => ['program_session'],
'hide_empty' => false,
'meta_query' => [
'relation' => 'AND',
'conference' => [
'key' => 'conference_id',
'value' => get_active_conf_id(),
'compare' => 'LIKE'
],
'session_start' => array(
'key' => 'program_session_start',
'type' => 'DATETIME',
),
],
'orderby' => 'session_start',
'order' => 'ASC',
] );
echo '<pre>';
print_r($term_query->terms);
Array
(
[0] => WP_Term Object
(
[term_id] => 67
[name] => Вкусный завтрак
[slug] => vkus
[term_group] => 0
[term_taxonomy_id] => 67
[taxonomy] => program_session
[description] =>
[parent] => 0
[count] => 0
[filter] => raw
)
[1] => WP_Term Object
(
[term_id] => 65
[name] => Хороший обед
[slug] => horoshij-obed
[term_group] => 0
[term_taxonomy_id] => 65
[taxonomy] => program_session
[description] =>
[parent] => 0
[count] => 0
[filter] => raw
)
[2] => WP_Term Object
(
[term_id] => 66
[name] => И просто ужин
[slug] => uzhin
[term_group] => 0
[term_taxonomy_id] => 66
[taxonomy] => program_session
[description] =>
[parent] => 0
[count] => 0
[filter] => raw
)
)
Answer the question
In order to leave comments, you need to log in
Non-kosher solution:
add_filter( 'get_terms_args', function ( $args, $taxonomies ) {
global $pagenow;
if ( is_admin() && $pagenow == 'edit-tags.php' && $taxonomies[0] == 'program_session' ) {
$args['menu_order'] = false;
$args['ignore_term_order'] = false;
$args['meta_query'] = [
'conference' => [
'key' => 'conference_id',
'value' => _get_active_conf_id(),
'compare' => 'LIKE'
],
];
}
return $args;
}, 10, 2 );
add_filter( 'terms_clauses', function ( $pieces, $taxonomies, $args ) {
global $pagenow, $wpdb;
if ( is_admin() && $pagenow == 'edit-tags.php' && $taxonomies[0] == 'program_session' ) {
$pieces['join'] .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';
$pieces['where'] .= ' AND tm.meta_key = "program_session_start"';
$pieces['orderby'] = ' ORDER BY tm.meta_value ';
}
return $pieces;
}, 10, 3 );
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question