0

I am using this filter to sort my query by a date field stored as text (legacy data)

add_filter( 'posts_orderby', 'my_posts_orderby_date', 10, 2 );
function my_posts_orderby_date( $orderby, $query ) {
    global $wpdb;
    return " CAST( $wpdb->postmeta.meta_value AS DATE ) " . $query->get( 'order' );
}

I need to tell this filter which meta_key to use, because it currently grabs the wrong meta key ($state_key) to sort on. How would I adjust this filter to do so?

i.e. I need to add this to the filter, somehow

$wpdb->postmeta.meta_key = 'tf_events_startdate'

Here is the original set of args, if it helps. Thank you!

$args = array(
            'post_type' => 'tf_events',         
            'meta_key' => $state_key,
            'meta_value' => $state_meta_value,
            'meta_query' => array( $relation, $date_query, $date_query2 ),
            'posts_per_page' => $limit, 
            'tax_query' => array( 'relation' => 'AND', $type_query, $host_query ),              
            'order' => 'ASC'
        );

1 Answer 1

0

Got the idea from this post to change my query : How to "orderby" the first array in a meta_query that uses multiply keys?

I moved the state query into the larger array of queries, freeing the 'meta_key' value to be assigned to event date

$args = array(
    'post_type' => 'tf_events',         
    'meta_query' => array( $relation, $date_query, $date_query2, $state_query ),
    'posts_per_page' => $limit, 
    'meta_key' => 'tf_events_startdate',
    'tax_query' => array( 'relation' => 'AND', $type_query, $host_query ),              
    'order' => 'ASC'
    );

add_filter( 'posts_orderby', 'my_posts_orderby_date', 10, 2 );
    function my_posts_orderby_date( $orderby, $query ) {
        global $wpdb;  
        return " CAST( $wpdb->postmeta.meta_value AS DATE ) " . $query->get( 'order' );
    }
1
  • Answer it man so people know that the answer was found.
    – aifrim
    Commented Nov 4, 2014 at 14:37

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.