• Resolved sparklogix

    (@mybenson)


    I’m a little perplexed here. We have a custom post type for “Events” and have a meta key for the Start Date. In our functions.php file, we have this:

    function respondo_events_archive_query( $query ) {
    	global $wp_query;
        if ( ! is_admin() && $query->is_main_query() && (is_post_type_archive('events') || is_tax('category-event'))) {
    		$query->set('orderby','meta_value');
    		$query->set('order','ASC');
    		$query->set('meta_key','event-date-start');
    	}
    }

    The posts sort correctly according to month and day, but when there are some 2014 events thrown in the mix, it puts the 2014 events first, although they are still ordered correctly by month and day, but the 2013 events should be first.

    If the order is ascending, I’m not sure why the later year events are showing up first. Thoughts on this? I hadn’t come across this before on previous sites (using a different theme).

Viewing 4 replies - 1 through 4 (of 4 total)
  • What is the format of the values in ‘event-start-date’? Dates will not sort properly unless they are stored with the year first, then month, then day.

    Thread Starter sparklogix

    (@mybenson)

    So the meta is set up to have the year last (see code below). Will anything be negatively affected if we change that to be YYYY/MM/DD on any events that are already created? I assume we’d need to manually adjust the meta value on all events already published? Would anything else need to be changed besides just moving the date format around?

    array(
            'id'        => 'event-date-start',
            'label'        => 'Start Date (MM/DD/YYYY)',
            'desc'        => 'The Start Date of the Event.',
            'std'        => '',
            'type'        => 'text',
            'class'        => ''
          ),

    Since I don’t know all the places where you use the date, I can’t tell if anything else will be affected.

    An alternative solution would be to modify the query to add a ‘rearranged’ date. I have not done this using the filter (pre_get_posts) that I think you are using, so I can’t give exact details just now.

    I have used the ‘posts_orderby’ filter to change the orderby to this:

    STR_TO_DATE($wpdb->postmeta.meta_value, '%d/%m/%Y') ASC
    Thread Starter sparklogix

    (@mybenson)

    Thanks @vtxyzzy

    I just switched up the meta key to use YYYY/MM/DD instead of MM/DD/YYYY and it worked. Such a simple fix.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Problem with CPT posts being sorted by date.’ is closed to new replies.