user3262824
user3262824

Reputation: 1

Call to undefined function get_user_meta() in wordpress

I have one file in wordpress theme folder. In that file I want to use get_user_meta() and update_user_meta function in that file. For which need to include. Because getting error:

Call to undefined function get_user_meta()

require( dirname( __FILE__ ) . '/../../wp-load.php' );

global $current_user;

wp_get_current_user();

$user_id= $current_user->ID;    

$user_data = get_user_meta($user_id);
$prev_reward_points = $user_data['reward_points'];
$new_reward_points = $prev_reward_points + 1000;

update_user_meta($user_id,"reward_points",$new_reward_points,$prev_reward_points);

echo "success";

exit;

Upvotes: 0

Views: 1587

Answers (2)

random_user_name
random_user_name

Reputation: 26160

If this file is in your theme folder, then there is no need to include wp-load.php - instead, the "right" way to do this following WordPress best practices is:

  1. Require this file inside of your theme (in your theme's functions.php file, add require_once 'this_file.php';)
  2. Place your existing code inside of a function (see below - I've made some changes to prevent errors in your code).
  3. Then, trigger this function in the manner that best suits your needs. Since you don't explain what you're doing, it's hard to know how to coach you in this area.

    function calculate_new_reward_points() {
    
        global $current_user;
    
        wp_get_current_user();
    
        $user_id= $current_user->ID;
    
        // no need to do this way... simplified version below
        // $user_data = get_user_meta($user_id);
    
        // see documentation for get_user_meta - can load the value directly
        $prev_reward_points = (int)get_user_meta( $user_id, 'reward_points', TRUE );     
    
        $new_reward_points = $prev_reward_points + 1000;
    
        // This will NOT store two values the way you have done it - based on your code above, I've modified this line below to work properly
        // update_user_meta($user_id, "reward_points", $new_reward_points, $prev_reward_points);
        update_user_meta($user_id, "reward_points", $new_reward_points );
    
        echo "success";
    }
    

Now, instead of wherever you were calling the file originally, you simply call calculate_new_reward_points(); - and you're done.

Upvotes: 0

Akshay Shah
Akshay Shah

Reputation: 3504

Put below line in the starting of you file. Instead of

require( dirname( FILE ) . '/../../wp-load.php' ); 

Place below code

include_once('../../../wp-load.php');

May i know why you are using because it is not required all things can be done without creating any custom file.

Upvotes: 2

Related Questions