Support » Plugins » Hacks » pre_get_posts and custom field values

  • Hi

    I am trying to use pre_get_posts to alter a query for a custom post type. I would like to order the results by the values of a custom field. My custom field is called “event_start_date” and a typical value is “02/12/2012 19:00”. The format of the string is dd/mm/yy h:i

    Is this possible using pre_get_posts and custom field values?

    The trouble I have is that the custom field holds this type of string value, and not a proper time stamp. So doing comparisons etc is difficult.

    Here is what I have cobbled together so far. However it is not ordering these posts by their ‘date’ order…

    function my_event_query( $query ) {
    	if( is_post_type_archive( 'events' ) ) {
    		$meta_query = array(
    				'key' => 'event_start_date',
    				'value' => time(),
    				'compare' => '>'
    		$query->set( 'meta_query', $meta_query );
    		$query->set( 'orderby', 'meta_value_num' );
    		$query->set( 'meta_key', 'event_start_date' );
    		$query->set( 'order', 'ASC' );
    		$query->set( 'posts_per_page', '-1' );
    add_action( 'pre_get_posts', 'my_event_query' );

    Is there any possibility of extracting the day/month/year time components so that I can order by date and time?

    Thanks in advance


Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz


    Not with ‘pre_get_posts’. You need to end up with a query that looks in part roughly like ...ORDERBY TIMESTAMP(wp_meta.value) ASC... but you can’t pass mysql functions as a query argument. So you need to either hook the action ‘posts_orderby’ to insert the function, or create your own sql query and use a $wpdb method. Either way, the reference I show to your meta value is wrong, the correct one will depend on how the meta table is joined and what, if any aliases are available.

    I don’t really know the exact syntax needed, mySQL is not part of my skill set, but this is the direction to pursue if you really need this.

    Thank you bcworkz for your response.

    Yes, looks like I need to rethink how I am going to do this. I will have a look at ‘posts_orderby’ and creating my own sql query.

    Thanks again

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘pre_get_posts and custom field values’ is closed to new replies.