自定义API端点从类别中获取数据

时间:2018-05-31 09:45:49

标签: wordpress api

我非常困难..我试图从使用Wordpress REST API获取特定类别ID的所有发布数据。但它不输出内容,只输出ID&标题..看不出我做错了什么..

下面是代码:

/* Register Route  http://dev.mpblogg.se/wp-json/api/v1/feedposts/id */
add_action( 'rest_api_init', function () {
    register_rest_route( 'api/v1', '/feedposts/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'getAllPostsfromCategory',
    ));
});


/* Get all posts from the specific Caetgory */
function getAllPostsfromCategory( $data ) {
$secret = '2lpMh5EHaEiavhMONpWD';
$qs = explode('&', $_SERVER['QUERY_STRING'])[0];
$qs = explode('=', $qs)[1];
if($qs != $secret){
    return false;
}
$posts = get_posts( array(
    'category' => $data['id'],
));

$returnArray = array();

foreach($posts as $post) {
    array_push($returnArray, array(
        'id'    =>      $post->ID,
        'title'     =>      $post->post_title,
        'content'   =>      $post->post_content
    ));
}

// die();

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

JSON输出如下所示:

enter image description here

更改为array_push($ returnArray,$ post);它看起来像这样:

enter image description here

2 个答案:

答案 0 :(得分:0)

好的......这是我从你共享的array_push图片中得到的线索。 JSON输出的最后一个字符串显示为:

  

&#34; filer&#34;:&#34; raw&#34;

这意味着结果值将存储为帖子的原始未经过滤的内容。

因此,您可以尝试将apply_filters()添加到提取的内容中,看看它是否有助于您显示所需的内容。

$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;

这用于将内容过滤器应用于原始未过滤的帖子内容,这通常来自使用$ post-&gt; post_content。

答案 1 :(得分:0)

像往常一样,为什么它没有工作的答案是如此愚蠢。我没有使用the_content ..我使用ACF的自定义字段名为post_excerpt。所以我刚补充说:

'excerpt'   =>  get_field('post_excerpt', $post->ID),

现在它有效..对不起,但感谢所有的帮助。