WordPress REST Api通过ID获取帖子

时间:2020-06-13 作者:psycho developer

嗨,我正在我的项目上建立WordPress rest API的自定义端点。我正在使用以下代码从网站获取单个响应。

function get_single_post( $request ) {
    
    $response = array();
    $args = [
        \'id\' => $request[\'id\'],
        \'post_type\' => \'payment\',
    ];
    $post = get_posts($args);

    $metas = get_post_meta($request[\'id\'],\'\');
    $post_id = $post->ID;

    $response[$post_id][\'response\'] = $post[0];
    $response[$post_id][\'metas\'] = $metas;

    return $response;
}

add_action(\'rest_api_init\', function(){
    register_rest_route(\'booking/v1\', \'posts\',[
        \'methods\'=> \'GET\',
        \'callback\' => \'booking_posts\',
    ]);
    
    register_rest_route(\'booking/v1\',\'/posts/(?P<id>\\d+)\',[
        \'methods\' => \'GET\',
        // Register the callback for the endpoint.
        \'callback\' => \'get_single_post\',
    ]);
});
我没有收到回复中的帖子。请告知我这里做错了什么?

以下是我的回答:

{
"": {
"response": {
"ID": 12042,
"post_author": "10",
"post_date": "2020-06-12 15:15:42",
"post_date_gmt": "2020-06-12 14:15:42",
"post_content": "",
"post_title": "xxxxxxxxxxxxxxx",
"post_excerpt": "",
"post_status": "publish",
"comment_status": "closed",
"ping_status": "closed",
"post_password": "",
"post_name": "xxxxxxxxxxx",
"to_ping": "",
"pinged": "",
"post_modified": "2020-06-12 15:15:42",
"post_modified_gmt": "2020-06-12 14:15:42",
"post_content_filtered": "",
"post_parent": 0,
"guid": "https://xxxxxxxx/payment/xxxxxxxxxx/",
"menu_order": 0,
"post_type": "payment",
"post_mime_type": "",
"comment_count": "0",
"filter": "raw"
},
"metas": {
"chauffeur_payment_status": [
"Unpaid"
],
"chauffeur_payment_num_passengers": [
"1"
],
"chauffeur_payment_num_bags": [
"0"
],
"chauffeur_payment_first_name": [
"xxxxxxx"
],
"chauffeur_payment_last_name": [
"xxxxxxxx"
],
"chauffeur_payment_email": [
"xxxxxxxxx"
],
"chauffeur_payment_phone_num": [
"xxxxxx"
],
"chauffeur_payment_flight_number": [
""
],
"chauffeur_payment_additional_info": [
""
],
"chauffeur_payment_pickup_address": [
"xxxxxxx"
],
"chauffeur_payment_dropoff_address": [
"xxxxxxxx"
],
"chauffeur_payment_pickup_date": [
"12/06/2020"
],
"chauffeur_payment_pickup_time": [
"12:00"
],
"chauffeur_payment_trip_distance": [
"3,907 km"
],
"chauffeur_payment_trip_time": [
"1 day 12 hours"
],
"chauffeur_payment_item_name": [
"Standard-size taxi"
],
"chauffeur_payment_trip_type": [
"one_way"
],
"chauffeur_payment_return_journey": [
"One Way"
],
"chauffeur_payment_num_hours": [
""
],
"chauffeur_payment_amount": [
"xxxx"
],
"chauffeur_payment_full_pickup_address": [
""
],
"chauffeur_payment_pickup_instructions": [
""
],
"chauffeur_payment_full_dropoff_address": [
""
],
"chauffeur_payment_dropoff_instructions": [
""
]
}
}
}
响应的id->;ID应与posts/相同。事实并非如此。

2 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

您得到的值不匹配,因为您在$args 数组(即WP_Query). 正确的论点是p (小写)P) 而不是id:

$args = [
//  \'id\' => $request[\'id\'], // wrong argument name - \'id\'
    \'p\' => $request[\'id\'],  // and the correct one is \'p\'
    \'post_type\' => \'payment\',
];
除了这个主要问题之外,我注意到的另一个问题是$post_id = $post->ID; 因此$post 是数组而不是对象。那么你是想用$post_id = $post[0]->ID; ?

还有,为什么要使用get_posts()? 为什么不直接使用get_post()$post = get_post( $request[\'id\'] ); ? 这样,上面$post_id = $post->ID; 将是有效的。例如,当使用get_post():

if ( ! $post = get_post( $request[\'id\'] ) ) {
    return new WP_Error( \'your_error_code_here\', \'Please define a valid post ID.\' );
}

$metas = get_post_meta( $request[\'id\'] );
$post_id = $post->ID;

$response[ $post_id ][\'response\'] = $post;

SO网友:Cameron

希望这对其他人有所帮助,这还使用了ACF自定义字段:

routes/site-route.php

<?php

class SiteRestRouter
{

  public function __construct()
  {
    $this->register_routes();
  }

  public function get_site($request)
  {
    $args = array(
      \'p\' => $request[\'id\'],
      \'post_type\' => \'site\',
    );

    if ( ! $post = get_post( $request[\'id\'] ) ) {
      return new WP_Error( \'invalid_id\', \'Please define a valid post ID.\' );
    }

    $query = new WP_Query($args);

    if ($query -> have_posts()) {
      $query->the_post();
      $post = get_post(get_the_ID());
      $id = get_the_ID();
      $title = $post->post_title;
      $last_updated = get_field(\'last_updated\');
      $deployment_location = get_field(\'location\');
      $git_location = get_field(\'git_location\');
      $database_location = get_field(\'database_location\');
      $host = get_field(\'host\');
      $protected_by_cloudflare = get_field(\'cloudflare\');
      $maintenance = get_field(\'maintenance\');
      $php_version = get_field(\'php_version\');
      $wordpress_version = get_field(\'wordpress_version\');
      $assigned_to = get_field(\'assigned_to\');
      $notes = get_field(\'notes\');
      $logs = get_field(\'logs\');

      $response[\'id\'] = $id;
      $response[\'title\'] = $title;
      $response[\'last_updated\'] = $last_updated;
      $response[\'deployment_location\'] = $deployment_location;
      $response[\'git_location\'] = $git_location;
      $response[\'database_location\'] = $database_location;
      $response[\'host\'] = $host;
      $response[\'protected_by_cloudflare\'] = $protected_by_cloudflare;
      $response[\'maintenance\'] = $maintenance;
      $response[\'php_version\'] = $php_version;
      $response[\'wordpress_version\'] = $wordpress_version;
      $response[\'assigned_to\'] = $assigned_to->post_title;
      $response[\'notes\'] = $notes;
      $response[\'logs\'] = $logs;
    }

    wp_reset_postdata();

    return $response;
  }

  protected function register_routes()
    {
      add_action(\'rest_api_init\', function () {
        $namespace = \'api/v1/\';

        register_rest_route($namespace, \'/sites/(?P<id>\\d+)\', array(
          \'methods\' => \'GET\',
          \'callback\' => array( $this, \'get_site\' ),
        ));
      });
    }
}

new SiteRestRouter();

Add this to functions.php

require_once \'routes/site-route.php\';

相关推荐

安装和卸载WP-REST-API插件后API返回空白响应

WordPress/WooCommerce API在我的网站上被破坏:http://example.com/wp-json/wp/v2/posts 和http://example.com/wp-json/wc/v2/products 两者都返回空白响应。运行Python请求response = requests.get(\'http://<mysite>.com/wp-json/wp/v2/posts\', auth=HTTPBasicAuth(*auth)) 给出的响应(在调试器中