2
votes

I have a custom post type fvc_members

Using advanced custom fields I've added a new field called user which is a relation object to an existing user.

I have the following code to query for the posts where the current user is set as user

$args = array(
    'numberposts' => 5,
    'post_type' => 'fvc_members',
    'meta_query' => array(
        array(
            'key'       => 'user',
            'value'     => '"' . get_current_user_id() . '"',
            'compare'   => '='
        )
    )
);

$posts = get_posts($args);

I've tried differnt options to write the value ( wrapped in '', wrapped in "", wihtout wrap, compare with LIKE ), however I can't find a way to get this working

2
Are you sure get_current_user_id() is not empty or null? Have you tried assigning it to a variable $mCurrentUserId = get_current_user_id() before the $args and then value => $mCurrentUserID?Antonios Tsimourtos
Try this -> $args = array( 'numberposts' => 5, 'post_type' => 'fvc_members', 'meta_query' => array( array( 'meta_key' => 'user', 'meta_value' => get_current_user_id(), ) ) );Antonios Tsimourtos
I output get_current_user_id() and i receive what i expectFrnak
Also try what you have, but without using compareAntonios Tsimourtos
that's working! thanks - feel free to post it as full answerFrnak

2 Answers

4
votes

Try $args without using the compare statement. You only need the key and the value which that makes it automatically a "compare" statement :

$args = array(
    'numberposts' => 5,
    'post_type' => 'fvc_members',
    'meta_query' => array(
        array(
            'key'       => 'user',
            'value'     => '"' . get_current_user_id() . '"',
        )
    )
);
2
votes

If user has only single integer value then you dont need the inverted comma, and also add the compare type.

Here is the code:

$args = [
    //...
    //...
    'meta_query' => [
        [
            'key' => 'user',
            'value' => get_current_user_id(),
            'compare' => '=',
            'type' => 'NUMERIC' //<-- add this
        ]
    ]
];
//...
$posts = get_posts($args);

Reference: Custom Field Parameters

Hope this helps!