Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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'
        );
share|improve this question

1 Answer 1

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' );
    }
share|improve this answer
    
Answer it man so people know that the answer was found. –  aifrim Nov 4 at 14:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.