Home › Forums › Front-end Issues › Match current user id to user relationship field
Trying to query posts were the current user is set in a user relationship field. Thought it would be easy but I am totally stuck.
I have tried this:
<?php $meta_query_args = array(
'relation' => 'AND',
array(
'key' => 'utfors_av',
'value' => $user_id,
'compare' => '='
)
);
$meta_query = new WP_Meta_Query( $meta_query_args );?>
But that just give me all the posts. utfors_av is my acf custom field name. Any ideas anyone?
Thanks!
are you doing this in a template or in a function outside of a template?
Also, I just noticed you are performing a meta_query, not a normal WP query.
I think you need to create a WP_Query
that contains a meta_query param.
Thanks
E
I am doing this inside a template (archive). I updated my code with WP_Query
<?php $user_id = get_current_user_id();
echo $user_id;?>
<?php $$args = array(
'post_type' => 'arende',
'meta_key' => 'utfors_av',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'utfors_av',
'value' => $user_id, //array
'compare' => '=',
)
)
);
$query = new WP_Query($args);;?>
But this returns the same result as mine did before.
I tried another approach – I get all posts and than I filter those that is right into one array and all others into another array. Is in fact better for my purposes. I have this code:
$arenden = new WP_Query( $args );
if ( $arenden->have_posts() ) :
while ( $arenden->have_posts() ) : $arenden->the_post();
$utfors_av = get_field('utfors_av');
$utfors = reset($utfors_av);
if($utfors == $user_id) {
array_push( $idmina, get_the_ID() );}
endwhile;
endif;
?>
The $args is just the standard, $idmina is the array I have setup were I want to store the IDs. But when I use this, I get an error:
Warning: reset() expects parameter 1 to be array, boolean given in ../archive-arenden.php on line 42
Line 42 is $utfors = reset($utfors_av).
When I use this on line 42 instead:
$utfors = strstr($utfors_av, ',', true);
I get another error saying it is an array.
Warning: strstr() expects parameter 1 to be string, array given in /home/almewebb/alpnet/wp-content/themes/enterprise-pro/archive-arenden.php on line 42
So what do I do wrong. Surely something trivial that I don’t see.
The topic ‘Match current user id to user relationship field’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.