WordPress does not find ‘User_ID’ and does not recognise logged-in status

I am still learning and hope you can help me. Specifically, it’s about me using two self-written plugins for WordPress to read whether a user is logged in or not. In the one plugin with success, the ID is recognised, then I am considered logged in and can also use the corresponding functions (set up search request). The other plugin is about the fact that I can only create a watchlist when I am logged in. Specifically, I click on a vehicle that I want to remember and can then add it to the watch list.

However, I am repeatedly told to log in for this action. However, I am already logged in, otherwise I would not be able to use the search request function, which works. I have checked the code several times and the console and error.logs show no anomalies. Do you have any idea how I can solve the problem?

The implementation of the plugin part where it is still assumed that I am not logged in looks like this:

// Add AJAX handlers for notepad functionality
function car_search_add_to_bookmark() {
    error_log('Function car_search_add_to_bookmark called. User ID: ' . get_current_user_id());
    global $wpdb;
    check_ajax_referer('car_search_nonce', 'nonce');

    // User must be logged in
    if (!is_user_logged_in()) {
        wp_send_json_error('User must be logged in.');
        wp_die();
    }

    $user_id = get_current_user_id();
    $carInfo = isset($_POST['carInfo']) ? $_POST['carInfo'] : null;

    if (!$carInfo || !is_array($carInfo)) {
        wp_send_json_error('Missing vehicle information.');
        wp_die();
    }

The implementation of the other plugin where the verification is already running successfully and recognises that I am logged in:

function rc_enqueue_plugin_scripts() {
    wp_register_script('rc-script', plugin_dir_url(__FILE__) . 'js/rc.js', array('jquery'), '1.0.0', true);
    wp_enqueue_script('rc-script');

    $nonce = wp_create_nonce('rc_nonce_action');

    wp_localize_script('rc-script', 'ajax_object', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => $nonce,
        'user_id' => get_current_user_id()
    ));
}
add_action('wp_enqueue_scripts', 'rc_enqueue_plugin_scripts');

Thank you so much!
Ben

Leave a Comment