Support

Account

Home Forums General Issues Relationship field: posts from author ID and meta_query

Helping

Relationship field: posts from author ID and meta_query

  • I have a relationship field displayed on certain posts and I want to populate it with articles only from a certain author ID.

    I also want to run a meta_query to check an array of IDs, and if this array finds an ID matching the author ID, to include the articles associated with it:

    
        function reference_sort( $args, $field, $post_id ) {
            $author_id = get_post_field ('post_author', $post_id);
            $args['author']= $author_id;
            $args['post_type'] = 'reference_cases';
            $args['orderby'] = 'date';
            $args['order'] = 'DESC';
            $args['posts_per_page'] = 40;
            $args['meta_query'] = array(
                'relation' => 'OR',
                array(
                    'key' => 'field_5f1ba9c9a725b',
                    'value' => $author_id,
                    'compare' => 'EXISTS',
                )
            );
            // return
            return $args;
        }
        add_filter('acf/fields/relationship/query/key=field_5f46f9c29272c', 'reference_sort', 10, 3);
    

    Everything works apart from the meta_query which breaks everything.

    I am using the EXISTS compare value because I assume it checks to see if the ID is in the key array.

    Does anyone know why this isn’t working? It’s my first time using meta_query but it seems to be correct from what I can find.

    Thanks

  • So you have several problems with this query.

    The first being that you cannot do
    {POST AUTHOR} OR {META QUERY} The query being run will always be {POST AUTHOR} AND {META QUERY} and it does not matter that you’ve added 'relation' => 'OR', to the meta query, this only effects the meta query itself. See this information on searching by content or custom fields, the concept here would be similar https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/

    What you need to do is, in your filter above you need to add additional add_filter(..... statements to perform the filtering that will alter the where part of the query in order to do{POST AUTHOR} OR {META QUERY}.

    When you get past that then the next issue it your use of “EXISTS” This just checks that the field exists in the DB and does not compare any value so any value specified is ignored. You are using a field that is stored as a serialized array of user IDs.

    You are also using the field key and not the field name, this will always return false because this meta_key value will never exist, you need to use the field name.

    What you need here is

    
    'meta_query' => array(
      array(
        'key' => 'field-name',
        'value' => '"'.$author_id.'"',
        'compare' => 'LIKE'
      )
    )
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.