Hello everyone,
I have a little problem.
I have a custom post type “objects” and i want to allow users to like those objects.
For that, i created a custom post type called “Likes” where i added one relationship field (relation to the object) named “relation_object” and one user field named “relation_user”.
In my page single-object, i’d like to know if this object is liked by the current user.
I don’t know how to do that.
I tried this but this doesn’t work :
$user = get_user_by('id', get_current_user_id());
$object = get_post(get_the_ID());
$like = get_posts(array(
'post_type' => 'likes',
'meta_query' => array(
array(
'key' => 'relation_user',
'value' => $user,
'compare' => '='
),
array(
'key' => 'relation_object',
'value' => $object,
'compare' => '='
)
)
));
Can someone help me please ?
Hi @mclambert
ACF saves an object (page, term, user, etc) as an ID in the database. Also, the relationship field saves the IDs in a serialized string. Could you please try the following query?
$like = get_posts(array(
'post_type' => 'likes',
'meta_query' => array(
array(
'key' => 'relation_user',
'value' => get_current_user_id(),
'compare' => '='
),
array(
'key' => 'relation_object',
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
)
));
This page should give you more idea about it: https://www.advancedcustomfields.com/resources/querying-relationship-fields/.
I hope this helps. 🙂
Ok thanks, it’s perfect !
I thought we had to give all the object to the query but only the ID is enough!
Thanks very much