Wordpress Wp Rest Api自定义端点POST请求

Wordpress Wp Rest Api自定义端点POST请求,wordpress,api,request,response,Wordpress,Api,Request,Response,我试图将一些数据发布到我创建的自定义api端点 这是我的wordpress自定义端点代码 register_rest_route( 'api/v1', '/cities', array( 'methods' => 'POST', 'callback' => 'create_city_from_data' )); 对于测试,我试图像这样返回请求 function create_city_from_data($req) { return ['req' => $

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

这是我的wordpress自定义端点代码

register_rest_route( 'api/v1', '/cities', array(
    'methods' => 'POST',
    'callback' => 'create_city_from_data'
));
对于测试,我试图像这样返回请求

function create_city_from_data($req) {
  return ['req' => $req];
}
{ name: 'Hello', population: 565656 }
但我总是收到空对象作为响应,无论我在有效载荷中发送什么,我都没有收到任何东西

我的有效载荷是这样的

function create_city_from_data($req) {
  return ['req' => $req];
}
{ name: 'Hello', population: 565656 }
这是从请求中收到的内容

{"req":{}}

通过使用此函数,您可以在API中查看自定义帖子类型的所有帖子。。。 在API查看器中获取所有帖子。 WriterURL在您的API查看器上(例如,我使用了Postman json API视图、google chrome adon)

这里的“hotel”是自定义的posttype

在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;

  } 
}
使用此功能,您可以从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);
}

传递到回调函数中的对象参数是一个对象,其上有一个
get\u body()
方法,该方法返回HTTP post请求的
payload/post body

function create_city_from_data(WP_REST_Request $req) {
  $body = $req->get_body()
  return ['req' => $body];
}
我今天在阅读时了解到了这一点


您还可以在方法签名中声明对象的类型,以防您需要在文档中搜索它(如上面所述)。

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

    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];
    }

我已使用postman查看POST参数

以及
$req->get_body_params()