Support

Account

Home Forums ACF PRO Query Posts by Relationship field and then orderby Date picker field

Solved

Query Posts by Relationship field and then orderby Date picker field

  • Hello,

    I’m struggling a bit trying to figure out how to write a proper meta_query.

    Here is the situation:

    On my site I have a CPTs called “podcasts” and “Team”. When creating a podcast, the user can select multiple authors using a relationship field to select any of the existing team members. In addition, the podcasts have a date field (date picker).

    Then on the team members single template, I want to show the member’s 3 most recent podcasts.

    So I need to query 3 podcasts where the current team member was selected and are ordered by the date picker field in descending order (3 most recent by date field). I’m pretty familiar with using meta_query to query posts by fields.

    If I was only querying by author, I would do something like:

    single-team.php

    $member_id = get_the_ID();
    
    $podcast_args = array(
        'post_type' => 'podcasts',
        'posts_per_page' => 3,
        'order' => 'DESC',
        'orderby' => 'date',
        'meta_query' => array(
            array(
                'key' => 'podcast_authors',
                'value' => $member_id,
                'compare' => 'LIKE'
            )
        )
    );

    The field name for the date picker is podcast_pub_date

    I know I will have to most likely need to pass an array to the orderby field or write an additional array in the meta_query. Just not sure the proper way to do it.

    Any help would be greatly appreciated.

    Thanks!

  • Hmmm, no replies at all. Geez, didn’t think my question was that out there.

    Anyways, if anyone else has the same question here is how ended solving my issue.

    $member_id = get_the_ID();
    $meta_query = array(
        array(
    	'key' => 'podcast_pub_date',
    	'value' => date('Ymd'),
    	'type' => 'DATE',
    	'compare' => '<='				   
        ),
        array(
    	'key' => 'podcast_authors',
    	'value' => $member_id,
    	'compare' => 'LIKE'
        )
    );
    			   
    $podcast_args = array(
        'post_type' => 'podcasts',
        'posts_per_page' => 3,
        'meta_key' => 'podcast_publication_date',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        'meta_query' => $meta_query
    );

    I don’t have a ton of test data yet and still are testing this but seems to be working as I need it to.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Query Posts by Relationship field and then orderby Date picker field’ is closed to new replies.