Matta301
Matta301

Reputation: 115

WordPress REST API Custom Endpoint for custom DB Query based on User ID

I’ve created a custom endpoint in WordPress where the callback calls a function to query a custom table, based on the logged in users ID. So the results will be specific for the logged in user.

The issue is, with my current code, If I make an api call to my local site through postman, it returns empty.

[] 

However, if I swap the $id variable in the query with a number, e.g. 11 (which matches a user id), it works and I get the intended results. It seems the data is getting lost at the callback stage.

I thought it might have been something to do with not having ‘permission callback’ set but this didn’t seem to make any difference. Can anyone shed any light?

function completed_peak() {
    
    $current_user = wp_get_current_user();
    $id    = esc_html( $current_user->ID );

    global $wpdb;
    $results = $wpdb->get_results("SELECT *
                                   FROM {$wpdb->prefix}custom_user_data
                                   WHERE user_id = $id",
                                   ARRAY_A
                                );
    return $results;
}

add_action( 'rest_api_init', 'user_completed_peaks');
function user_completed_peaks() {
    register_rest_route( 'wp/v2', '/custom_user_data', array(
        'methods' => 'GET',
        'callback' => 'completed_peak'
    ));
}

Upvotes: 0

Views: 1600

Answers (1)

Hamiru
Hamiru

Reputation: 1

Try this: Put the $id in the SELECT statement in quotes: '$id'. Not logical to me, but for my SELECT-statements this is what works. For example: "SELECT `titel` FROM `table` WHERE `titel` = '$san_title_given' "

Upvotes: 0

Related Questions