Incrementally add or substract from usermeta field

I’m trying to create a system to add credits to a user account and then later subtract from the credits when the user submits a post.

I have the functions I need to trigger the adding credits and the removing of credits, I just need help with the actual code to get that part done.

Read More

This is what I want to do:

Adding credit

  1. Set a variable called “add_credit_amount” with amount of credit to be added.

  2. Get the current user’s ID

  3. Get current users meta field value stored in the “my_user_credit” field

  4. Add the “add_credit_amount” variable to the “my_user_credit” amount

  5. Update the users “my_user_credit” field with the new amount.

Removing credit

  1. Create a variable called “remove_credit_amount” and set the amount of credit to be removed.

  2. Get the current user’s ID

  3. Get current users meta field value stored in the “my_user_credit” field

  4. Check to see if the value in the “my_user_credit” field is greater than or equal to the “remove_credit_amount“.

  5. If it is then subtract the “remove_credit_amount” variable from the “my_user_credit” field amount and update the users “my_user_credit” field with the new amount.

  6. If it is not then echo this message: “You do not have enough credits to post.”


Thanks in advance to anyone who can help.

UPDATE

@JoshuaAbenazer

I’m trying to get this to work. I don’t want to show the form if they don’t have enough credits. Can you see why it does not work right? It does not seem to return the value for the meta field.

Thanks

<?php 
global $user_ID;
$user_ID = wp_get_current_user();
$creditcount = get_user_meta( $user_ID, 'my_user_credit', true );
if($creditcount <= 4){
echo 'please get more credits';
} else {
echo do_shortcode('[gravityform id=2 title=false description=false]');
}

?>

Thanks

Related posts

Leave a Reply

1 comment

  1. The function below should do your job.

    function manage_credits( $operation = 'add', $amount = 0 ) {
        $user_id = get_current_user_id();
    
        if ( $user_id ) {
            $user_credit = (int) get_user_meta( $user_id, 'my_user_credit', true );
    
            if ( 'add' == $operation ) {
                $user_credit += $amount;     //For adding credits
            } elseif ( 'remove' == $operation && ( $user_credit >= $amount ) ) {
                $user_credit -= $amount;     //For removing credits
            } elseif ( 'remove' == $operation ) {
                echo 'You do not have enough credits to post.';
                return;
            }
            update_user_meta( $user_id, 'my_user_credit', $user_credit );
        }
    }
    

    Now all you need to do is while triggering add you will call manage_credits( 'add', 10 ) and while triggering remove you will call manage_credits( 'remove', 10 ). The second parameter should be passed with the amount of credit you would like to add or remove.