Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wp Rest Api Custom End point POST request

Im trying to post some data to custom api endpoint that i created,

This is what my wordpress custom endpoint code.

register_rest_route( 'api/v1', '/cities', array(
    'methods' => 'POST',
    'callback' => 'create_city_from_data'
));

And for testing I am trying to return the request like this

function create_city_from_data($req) {
  return ['req' => $req];
}

but always i receive empty object as response, whatever i send in payload i didn't receive anything.

My payload is something like this

{ name: 'Hello', population: 565656 }

This is what is received from the request

{"req":{}}
like image 782
Wimal Weerawansa Avatar asked Dec 28 '16 12:12

Wimal Weerawansa


3 Answers

By using below code you can view your payload.

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

I have used postman to view the POST parameter

like image 61
Bhoomi Joshi Avatar answered Oct 19 '22 07:10

Bhoomi Joshi


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

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;

  } 
}

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);
}
like image 12
Dipak Mahajan Avatar answered Oct 19 '22 07:10

Dipak Mahajan


The object parameter passed into the callback function is a WP_REST_REQUST object and has a get_body() method on it which returns the payload/post body of the HTTP Post Request.

function create_city_from_data(WP_REST_Request $req) {
  $body = $req->get_body()
  return ['req' => $body];
}

I learnt about this today whilst reading this article

You can also declare the type of object in the method signature in case you need to search the documentation for it (like i have above).

like image 6
Max Carroll Avatar answered Oct 19 '22 08:10

Max Carroll