• Resolved htausch

    (@htausch)


    I would like to sort by the date in the custom date picker if present or the publish date if not.

    Example:

    August 2016
    Custom Date Picker

    March 2016
    Post Publish Date

    February 2016
    Custom Date Picker

    I have gotten this to work partially by using the following code:

    $queryArgs = array(
    	'post_type'      => 'portfolio',
    	'meta_key'	 => 'event_start_date',
    	'orderby'	 => 'meta_value_num date',
    	'order'		 => 'DESC',
    );

    However, this sorts by custom date then post date. So the result looks like this:

    August 2016
    Custom Date Picker

    February 2016
    Custom Date Picker

    March 2016
    Post Publish Date

    I spoke to James at ACF and he suggested this might be because they save in two different formats. So I used the following code to determine what formats they save in:

    <?php echo get_field('event_start_date') ?> <br>
    <?php the_date(); ?>

    This resulted in:

    20160803
    March 24, 2016

    So I am thinking I either need to save both as a variable with modified formats and then feed them into my loop OR, as James suggested (and which I am utterly confused how to do).

    “You can always create a dummy date field for your news and set the published date automatically using the “acf/save_post” hook and the update_field() function. That way, you only need to order by the custom field, which should have the same structure in the database.

    I’m not sure how to use either…

    https://wordpress.org/plugins/advanced-custom-fields/

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter htausch

    (@htausch)

    Solved it! In functions.php:

    function acf_update_date($post_ID) {
            $datepicker = get_field('event_start_date', $post_ID);
            if($datepicker) {
                    $date = $datepicker;
            } else {
                    $date = get_the_time('Ymd', $post_ID);
            }
    
            update_field('event_start_date', $date, $post_ID);
    }
    add_action('acf/save_post', 'acf_update_date', 20);

    In loop:

    $queryArgs = array(
    	'post_type'      => 'portfolio',
    	'meta_key'	 => 'event_start_date',
    	'orderby'	 => 'meta_value_num',
    	'order'		 => 'DESC',
    );

    Thanks for this htausch! Any idea how to use this in an index where there are several post types and only one of them uses ACF as the date that should be considered for sorting – ?

    David

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Sorting by custom field date and post date?’ is closed to new replies.