Look a this code:
if( isset( $_POST [ 'add_like' ] ) ){
$update = $like_value + '1';
update_post_meta($post_id, '_like_value', $update, $like_value);
}
Because you’re using it in a loop, it gets output multiple times on a page with a different value for $post_id
each time. So essentially you have this:
if( isset( $_POST [ 'add_like' ] ) ){
update_post_meta(1, '_like_value', $update, $like_value);
}
if( isset( $_POST [ 'add_like' ] ) ){
update_post_meta(2, '_like_value', $update, $like_value);
}
if( isset( $_POST [ 'add_like' ] ) ){
update_post_meta(3, '_like_value', $update, $like_value);
}
So consider what happens when there is a value for $_POST [ 'add_like' ]
. All those if
s will be true
so every one of those updates is going to run.
Now really you should be separating the logic of handling the updating and the template. Mixing them up like this is a recipe for trouble. But the main reason your code isn’t working the way you like is because your form isn’t submitting which post to like.
You need to add a hidden input with the correct post ID, and check which post needs to be updated before updating.
So add the input to your form:
<form name="update_post" method="POST" action="">
<button type="submit" name="add_like"><i class="fa fa-heart"></i></button>
<input name="post_id" type="hidden" value="<?php echo esc_attr( $post_id ); ?>">
</form>
Then before updating, check that the submission was for the current post:
<?php if( isset( $_POST['add_like'] ) && isset( $_POST['post_id'] ) && $_POST['post_id'] === $post_id ) {
$update = $like_value + '1';
update_post_meta($post_id, '_like_value', $update, $like_value);
} ?>