I am trying to get custom term meta value for a certain category using get_term_meta() function. This value is stored in the wp_termmeta table. Then, based on that value, I want to modify the main query for a certain category archive page (sort the posts by date ascending). However, the pre_get_posts() hook that I am using does not allow me to do so. I tried all the ways that i am aware of, however, it is still not working
Here is my code:
function my_new_category_order( $query ) {
//get the category id
$cat_id = get_query_var('cat');
//get the custom meta value
$post_order = get_term_meta($cat_id, 'post-order', true);
//The value is shown two times. First, it is false, then it is "oldest"
var_dump($post_order);
//Cannot go inside the if statement because $post_order is false!
if ( $post_order && $query->is_category($cat_id) && $query->is_main_query() ) {
$query->set( 'order', 'ASC' );
//$post_order is false here
var_dump($post_order);
//$cat_id is empty string
var_dump($cat_id);
}
}
add_action( 'pre_get_posts', 'my_new_category_order' );
As a result, I am not able to go inside the if statement and reorder the posts.. The rest of the code is working fine but the term meta value remains undefined. What am I doing wrong?