This is an odd situation. I’m trying to make a pseudo like/follow functionality on a membership site using ACF.
I have gotten it to display the liked/followed user from a user object field within the backend. I now need to build a button that I can add to all users profile pages that will allow the user to like/follow that user, which will add to their user field within their own profile page on the frontend and update it all in one go.
Any ideas on how this can be done? I’ve not found anything on my initial searches.
I've tried building out an ACF Form but its not updating the options. I've also tried this code:
$current_user = wp_get_current_user();
add_action('acf/save_post', 'update_name');
function update_name($current_user) {
if (get_post_type($current_user) != 'user_follows') {
return;
}
$field_key = "field_63d0017ab088f";
$value = get_the_author_meta('user_nicename');
update_field( $field_key, $value, $current_user);
}
and then firing it with an input submit button:
<input type="submit" class="acfef-submit-button acf-button button button-primary" data-state="publish" value="Follow">
Sadly this didn't work either.
Anyone have any ideas how I can get this working?
Any help would be great!
This is a pretty simple solution that you can tailor to your needs or maybe just help you on your way in how you were originally trying it. I wasn't sure how you were going about it from your original and guessed it could be solved with a simple form using update_field
. I'd definitely build this with REST API if I was doing it myself. I've just dumped the code below, let me know if it makes sense and/or works for you, if you need I can add comments if required, just updating the $user_likes
array to update the field based off the value of the submit button.
I built this on my local install and asuming you are using some variation of the author.php template file.
<?php
$profile_user = get_queried_object();
$current_user = wp_get_current_user();
$current_user_slug = 'user_' . $current_user->ID;
$field_key = "field_63d0017ab088f";
$user_likes = [];
if(get_field('user_follows', $current_user_slug)){
$user_likes = get_field('user_follows', $current_user_slug);
}
if(isset($_POST['follow'])){
if($_POST['follow'] === 'Unfollow'){
$key = array_search($profile_user, $user_likes);
unset($user_likes[$key]);
update_field($field_key, $user_likes, $current_user_slug);
}elseif($_POST['follow'] === 'Follow'){
$user_likes[] = $profile_user;
update_field($field_key, $user_likes, $current_user_slug);
}
}
$but_val = 'Follow';
if (in_array($profile_user, $user_likes)) {
$but_val = 'Unfollow';
}
?>
<form method="post">
<input type="submit" name="follow" value="<?= $but_val; ?>">
</form>