Wp Rest Api自定义端点POST请求

Wim*_*nsa 6 api wordpress response request

我试图将一些数据发布到我创建的自定义api端点,

这就是我的wordpress自定义终结点代码。

register_rest_route( 'api/v1', '/cities', array(
    'methods' => 'POST',
    'callback' => 'create_city_from_data'
));
Run Code Online (Sandbox Code Playgroud)

为了测试,我正在尝试像这样返回请求

function create_city_from_data($req) {
  return ['req' => $req];
}
Run Code Online (Sandbox Code Playgroud)

但总是我收到一个空对象作为响应,无论我发送的有效载荷是什么,我什么都没有收到。

我的有效载荷是这样的

{ name: 'Hello', population: 565656 }
Run Code Online (Sandbox Code Playgroud)

这是从请求中收到的

{"req":{}}
Run Code Online (Sandbox Code Playgroud)

小智 12

通过使用以下代码,您可以查看您的有效负载。

    add_action('rest_api_init', function () {
        register_rest_route( 'api/v1', '/cities', array(
            'methods' => 'POST',
            'callback' => 'create_city_from_data'
        ));
    });
    function create_city_from_data($req) {
        $response['name'] = $req['name'];
        $response['population'] = $req['population'];

        $res = new WP_REST_Response($response);
        $res->set_status(200);

        return ['req' => $res];
    }
Run Code Online (Sandbox Code Playgroud)

我已经使用邮递员查看POST参数


Max*_*oll 9

传递到回调函数中的对象参数是一个WP_REST_REQUST对象,并且有一个get_body()返回payload/post bodyHTTP Post 请求的方法。

function create_city_from_data(WP_REST_Request $req) {
  $body = $req->get_body()
  return ['req' => $body];
}
Run Code Online (Sandbox Code Playgroud)

今天我在阅读这篇文章时了解到了这一点

您还可以在方法签名中声明对象的类型,以防您需要搜索它的文档(就像我上面的那样)。


Dip*_*jan 7

By using this function you can see all post of your custom post type in API... Get All Post in your API Viewer. Writer URL on your API viewer (e.g. I used Postman json api view, google chrome adon)

Domain-name/wp-json/showFavorites/v2?post_type=hotel
Run Code Online (Sandbox Code Playgroud)

Here 'hotel' is the custom posttype.

Add this function in your functions.php

add_action( 'rest_api_init', 'wp_api_show_favorites_endpoints' );
function wp_api_show_favorites_endpoints() {
  register_rest_route( 'showFavorites', '/v2', array(
        'methods' => 'GET',
        'callback' => 'showFavorites_callback',
    ));
}
function showFavorites_callback( $request_data ) {
  global $wpdb;
    $data = array();

    $table        = 'wp_posts';
  $parameters = $request_data->get_params();
  $post_type = $parameters['post_type'];

  if($post_type!=''){
      $re_query     = "SELECT * FROM $table where post_type='$post_type'";
      $pre_results  = $wpdb->get_results($re_query,ARRAY_A);   
      return $pre_results;

  }else{
      $data['status']=' false ';
      return $data;

  } 
}
Run Code Online (Sandbox Code Playgroud)

And using this you can post your content from API

        // POST All Posts using API
add_action( 'rest_api_init', 'wp_api_add_posts_endpoints' );
function wp_api_add_posts_endpoints() {
  register_rest_route( 'addPost', '/v2', array(
        'methods' => 'POST',
        'callback' => 'addPosts_callback',
    ));
}
function addPosts_callback( $request_data ) {
  global $wpdb;
  $data = array();
  $table        = 'wp_posts';

  // Fetching values from API
  $parameters = $request_data->get_params();
  $user_id = $parameters['user_id'];
  $post_type = $parameters['post_type'];
  $post_title = $parameters['post_title'];
  $the_content = $parameters['the_content'];
  $cats = $parameters['cats'];
  $the_excerpt = $parameters['the_excerpt'];
  $feature_img = $parameters['featured_image'];

  // custom meta values
  $contact_no = $parameters['contact_no'];
  $email = $parameters['email'];
  $hotel_url = $parameters['hotel_url'];


  if($post_type!='' && $post_title!=''){

      // Create post object
      $my_post = array(
        'post_title' => wp_strip_all_tags( $post_title),
        'post_content' => $the_content,
        'post_author' => '',
        'post_excerpt' => $the_excerpt,
        'post_status' => 'publish',
        'post_type' => $post_type,
      );
      $new_post_id = wp_insert_post( $my_post );


      function wp_api_encode_acf($data,$post,$context){
          $customMeta = (array) get_fields($post['ID']);

           $data['meta'] = array_merge($data['meta'], $customMeta );
          return $data;
      }

      if( function_exists('get_fields') ){
          add_filter('json_prepare_post', 'wp_api_encode_acf', 10, 3);
      }


      // Set post categories
      $catss = explode(',', $cats);
      if (!empty($catss)) {
        if ($post_type == 'post') {
          wp_set_object_terms( $new_post_id, $catss, 'category', false );
        }
        else{
          wp_set_object_terms( $new_post_id, $catss, 'Categories', false );   // Executes if posttype is other
        }
      }

      // Set Custom Metabox
      if ($post_type != 'post') {
        update_post_meta($new_post_id, 'contact-no', $contact_no);
        update_post_meta($new_post_id, 'email', $email);
        update_post_meta($new_post_id, 'hotel-url', $hotel_url);
      }

      // Set featured Image
      $url = $feature_img;
      $path = parse_url($url, PHP_URL_PATH);
      $filename = basename($path);

      $uploaddir = wp_upload_dir();
      $uploadfile = $uploaddir['path'] . '/' . $filename;

      $contents= file_get_contents($feature_img);
      $savefile = fopen($uploadfile, 'w');
      chmod($uploadfile, 0777);
      fwrite($savefile, $contents);
      fclose($savefile);

      $wp_filetype = wp_check_filetype(basename($filename), null );

      $attachment = array(
          'post_mime_type' => $wp_filetype['type'],
          'post_title' => $filename,
          'post_content' => '',
          'post_status' => 'inherit'
      );

      $attach_id = wp_insert_attachment( $attachment, $uploadfile );

      if ($attach_id) {
        set_post_thumbnail( $new_post_id, $attach_id );
      }

      if ($new_post_id) {
          $data['status']='Post added Successfully.';  
      }
      else{
        $data['status']='post failed..';
      }

  }else{
      $data['status']=' Please provide correct post details.';
  }

  return ($data);
}
Run Code Online (Sandbox Code Playgroud)