0

I have a button on the frontend that updates the value of post meta on the backend, and it's nested inside a loop.

However, on submit it updates the value on ALL posts. What am I doing wrong?

function post_likes(){ 
global $post;
$post_id = $post->ID;
$like_value = get_post_meta($post_id, '_like_value', true);
?>
<div id="post-input-options">
    <div id="like_post">
        <form name="update_post" method="POST" action="">
            <button type="submit" name="add_like"><i class="fa fa-heart"></i></button>
        </form>
        <?php if( isset( $_POST [ 'add_like' ] ) ){
            $update = $like_value + '1';
            update_post_meta($post_id, '_like_value', $update, $like_value);
        } ?>
    </div>
</div>
<div id="post-input-info">
    <?php if( $like_value[ '_like_value' ][ '0' ] != "" ){
        echo $like_value . ' likes';
    } else {
        echo '0 likes';
    } ?>
</div>

0

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 ifs 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);
} ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.