簡體   English   中英

WP REST API自定義端點如何返回自定義帖子數據?

[英]How WP REST API custom endpoint could return custom post data?

TL; DR :如何選擇WP REST API自定義端點的響應的所有信息?

長版

如果我想使用WP REST API構建自定義端點-從不同的帖子類型發送特定的帖子數據-按照手冊中的示例進行操作,我得到了:

function custom_endpoint ( $data ) {
    $posts = get_posts( array(
        'numberposts'   => -1,
        'post_type'     => array('event', 'post'),
    ) );

    if ( empty( $posts ) ) {
        return null;
    }

    return $posts;
}


add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v1', '/custom-endpoint/', array(
        'methods' => 'GET',
        'callback' => 'custom_endpoint',
    ) );
} );

但是get_post()函數不會返回某些非常有用的數據,如果您希望在頁面中顯示帖子(類別ID,特色圖片,例如)。 因此,如何構建一個返回以下內容的自定義端點:

  • 帖子標題
  • 發布日期
  • 發表作者
  • 摘錄后
  • 帖子內容
  • 發布特色圖片(如“ 更好的特色圖片”插件
  • 帖子類別
  • 帖子類型
  • 發布鏈接
  • 其他有用信息

基於@fsn答案,我有以下想法:拿取get_posts()返回的對象,並使用其他Wordpress函數向其添加新的比例。

function custom_endpoint ( $data ) {
$posts = get_posts( array(
    'numberposts'   => -1,
    //Here we can get more than one post type. Useful to a home page.
    'post_type'     => array('event', 'post'), 
) );


if ( empty( $posts ) ) {
    return null;
}


$args = array();    

foreach ( $posts as $post ) {

 //Get informations that is not avaible in get_post() function and store it in variables.
   $category = get_the_category( $post->ID );
   $img_thumb = get_the_post_thumbnail_url( $post->ID, 'thumbnail' );       // Thumbnail (default 150px x 150px max)
   $img_medium = get_the_post_thumbnail_url( $post->ID, 'medium' );          // Medium resolution (default 300px x 300px max)
   $img_large = get_the_post_thumbnail_url( $post->ID, 'large' );           // Large resolution (default 640px x 640px max)
   $img_full = get_the_post_thumbnail_url( $post->ID, 'full' );            // Full resolution (original size uploaded)

 //Adds the informations to the post object.
   $post->category = $category; 
   $post->img_tumb = $img_thumb; 
   $post->img_medium = $img_medium; 
   $post->img_large = $img_large; 
   $post->img_full = $img_full;

   array_push($args, $post);
   }
return $args;
}
add_action( 'rest_api_init', function () {
  register_rest_route( 'wp/v1', '/custom-endpoint/', array(
    'methods' => 'GET',
    'callback' => 'custom_endpoint',
) );

});

工作正常!

謝謝@fsn的貢獻。

WP Codex聲明要訪問所有數據:

訪問所有帖子數據某些與帖子相關的數據不可用於 get_posts。

您可以通過以下方式獲得它們:

$posts = get_posts( array(
        'numberposts'   => -1,
        'post_type'     => array('event', 'post'),
    ) );

$response = [];
foreach ( $posts as $post ) {
  $response[] = [
    'content' => $post->CONTENT.
     'title' =>  $post->TITLE,
      .....
  ]
}

return $response; (in a WP way of constructing json responses)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM