Rest_cookie_invalid_nonce - Cookie check failed - Wordpress ACF pro update current logged in user meta fields

60 views Asked by At

Trying to update a repeater field that is part of a custom field group from ACF pro. The field group "show in rest api" is enabled. The condition of the field group is "current user is logged in".

Made a custom post type with ACF, when a logged in user visits the custom post type single page template, the user should be able to click a button "book flight" which will trigger the javascript to trigger a post request with the title of the current post. The javascript will update the user meta field repeater field so users can have an overview of all the booked flights.

The issue that arises, is & 403 forbidden. The request url is https://www.doamainname.com/wp-json/acf/v3/users/14 and the header contains a valid X-Wp-Nonce. But it seems the nonce is always the same (caching turned off). The error that I get is:

{
    "code": "rest_cookie_invalid_nonce",
    "message": "Cookie check failed",
    "data": {
        "status": 403
    }
}

**Code setup: **

  1. Enqueu scripts, using the wp_create_nonce("acf") in a php file with the code snippets plugin set to "run snippet everywhere".
function enqueue_custom_scripts() {
// Enqueue JavaScript file
wp_enqueue_script('your-script-handle', get_template_directory_uri() . '/custom/dzdze512/js/custom-fetch-file.js', array('jquery'), null, true);

// Pass the user ID to the JavaScript
wp_localize_script('your-script-handle', 'userData', array(
'userId' => get_current_user_id()
));

}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

function localize_custom_script() {
// Get the ACF nonce
$acf_nonce = wp_create_nonce('acf');

// Define the data to pass to JavaScript
$script_data = array(
'nonce' => $acf_nonce
);

// Localize the script with the data
wp_localize_script('your-script-handle', 'acfData', $script_data);
}
add_action('wp_enqueue_scripts', 'localize_custom_script');
  1. javascript file in file directory:
// JavaScript function to send a POST request to add a subfield to the "my_flights" repeater field
function addSubfieldToMyFlights() {
  // Get the flight name from the current post
  var flightName = "<?php echo get_the_title(); ?>"; // Use PHP to fetch the flight name
  // Create a field name by replacing spaces with underscores
  var fieldName = flightName.replace(/ /g, '_');

  // Prepare the data to send in the request
  var postData = {
    fields: {
      'my_flights_customer': [ // Use the actual field name
        {
          // Add a subfield of type text with label and field name
          'subfield': {
            field_type: 'text',
            field_label: flightName, // Label based on the post title
            field_name: fieldName // Field name with spaces replaced by underscores
          }
        }
      ]
    }
  };
  
  // Access the user ID from the localized script data
  var currentUserId = userData.userId;
  
  // Construct the URL for the fetch request
  var url = '/wp-json/acf/v3/users/' + currentUserId;

  // Send a POST request to the ACF REST API using the constructed URL
  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-WP-Nonce': acfData.nonce, // Include a nonce for security
    },
    body: JSON.stringify(postData),
  })
  .then(response => response.json())
  .then(data => {
    // Handle the response if needed
  });
}
  1. Handling of post request in a php file with the code snippets plugin set to "run snippet everywhere".
// PHP function to handle the POST request and update the "my_flights_customer" repeater field
function handleAddSubfieldToMyFlights() {
  if (is_user_logged_in() && isset($_POST['fields']['my_flights_customer'])) {
    $user_id = get_current_user_id();
    $my_flights_customer = get_field('my_flights_customer', 'user_' . $user_id); // Get the current "my_flights" data

    // Add the new subfield to the existing "my_flights_customer" data
    $newSubfield = array(
      'field_key' => 'field_' . uniqid(), // Generate a unique field key
      'field_type' => 'text',
      'field_name' => sanitize_title(get_the_title()), // Field name based on the post title
      'field_label' => get_the_title() // Label based on the post title
    );

    if (empty($my_flights_customer)) {
      $my_flights_customer = array(); // Initialize the "my flights" repeater field if it's empty
    }

    $my_flights_customer[] = $newSubfield;

    // Update the user's "my_flights_customer" repeater field
    update_field('my_flights_customer', $my_flights_customer, 'user_' . $user_id);

    // Send a response if needed
  }
}

add_action('wp_ajax_add_subfield_to_my_flights', 'handleAddSubfieldToMyFlights');

I have tried using the wp_rest action, but using this sets me back a step. As the error in that case is a 404 not found. Meaning the url is not build correctly when using wp_rest action and ScoreSettings.nonce.

Does anyone know how to fix this?

0

There are 0 answers