WordPress

php — Zarejestrowałem trasę REST, ale otrzymuję 400 złych żądań

  • 19 czerwca, 2023
  • 3 min read
php — Zarejestrowałem trasę REST, ale otrzymuję 400 złych żądań


Jestem w tym nowy, więc proszę, obnażaj się ze mną. Próbuję zarejestrować trasę REST, aby zapisać dynamicznie dodawane niestandardowe pola niestandardowego postu wraz z postem, gdy użytkownik kliknie przycisk „Aktualizuj” w edytorze bloków. Nie wiem, co robię źle. Otrzymałem kod z ChatGPT i dostosowałem go zgodnie z moją najlepszą wiedzą, ale wciąż daje mi 400 złych żądań na konsoli.

Oto mój kod JavaScript:

document.addEventListener('DOMContentLoaded', function() {
  // Delete location event handler
  
  // Add a location event handler

  // Watch out for the save action
  wp.data.subscribe(function() {
    var editor = wp.data.select('core/editor');
    if (!editor) return;
    if (editor.isSavingPost() && !editor.isAutosavingPost()) {
      var locationsData = [];

      // Retrieve all the locations from the DOM
      var locationItems = document.querySelectorAll('.location-item');
      if (locationItems.length > 0) {
        locationItems.forEach(function(locationItem) {
          var i = locationItem.dataset.index;
          var locationData = {
            name: locationItem.querySelector('input[name^="guide-locations-' + i + '"]').value,
            description: wp.editor.getContent('guide-locations-' + i + '-description'),
            map: locationItem.querySelector('input[name^="guide-locations-' + i + '-map"]').value,
            wifi: locationItem.querySelector('input[name^="guide-locations-' + i + '-wifi"]').value,
            price: locationItem.querySelector('input[name^="guide-locations-' + i + '-price"]').value,
            hours: locationItem.querySelector('input[name^="guide-locations-' + i + '-hours"]').value,
          };
          locationsData.push(locationData);
        });
      }

      // Send a POST request to update the post meta
      fetch(guidePostsAjax.ajaxUrl + '/guide-posts/v1/save-locations/' + editor.getCurrentPostId(), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-WP-Nonce': guidePostsAjax.nonce
        },
        body: JSON.stringify(locationsData)
      })
      .then(function(response) {
        if (!response.ok) {
          throw new Error('An error occurred');
        }
        return response.json();
      })
      .then(function(data) {
        // Handle the response
        console.log(data);
      })
      .catch(function(error) {
        console.error('An error occurred:', error);
      });
    }
  });

});

Oto kod PHP związany z wtyczką:

// Register a custom REST route for saving guide locations
function save_guide_locations_rest_route() {
  register_rest_route(
    'guide-posts/v1',
    '/save-locations/(?P<post_id>\d+)',
    array(
      'methods' => 'POST',
      'callback' => 'save_guide_locations',
    )
  );
}
add_action( 'rest_api_init', 'save_guide_locations_rest_route' );

// REST handler for saving guide locations
function save_guide_locations( $request ) {
  $post_id = $request->get_param( 'post_id' );

  // Validate parameter
  if ( empty( $post_id ) ) :
    return new WP_Error( 'invalid_params', 'Invalid parameters.', array( 'status' => 400 ) );
  endif;

  // Verify the nonce
  if ( ! isset( $_POST['guide_locations_nonce'] ) || ! wp_verify_nonce( $_POST['guide_locations_nonce'], 'guide_locations_nonce' ) ) :
    return new WP_Error( 'invalid_nonce', 'Invalid nonce.', array( 'status' => 403 ) );
  endif;

  // Get the locations data from the request body
  $body = $request->get_body();
  $locations_data = json_decode( $body, true );

  // Check if decoding the JSON was successful
  if ( is_null( $locations_data ) ) {
    return new WP_Error( 'json_decode_error', 'Failed to decode JSON data.', array( 'status' => 400 ) );
  }

  // Sanitize and save the locations data
  update_post_meta( $post_id, 'guide_locations', $locations_data );

  return array( 'message' => 'Guide locations saved successfully.' );
}

W większości rozumiem kod. Po prostu nie wiem, co robię źle.

Warto przeczytać!  WooCommerce Motyw WordPress Porady SEO: przewodnik dla początkujących


Źródło