我创建了一个自定义RESTAPI来获取帖子
add_action( \'rest_api_init\', \'custom_api_get_all_posts\' );
function custom_api_get_all_posts() {
register_rest_route( \'custom/v1\', \'/all-posts\', array(
\'methods\' => \'GET\',
\'callback\' => \'custom_api_get_all_posts_callback\'
));
}
function custom_api_get_all_posts_callback( $request ) {
// Initialize the array that will receive the posts\' data.
$posts_data = array();
// Receive and set the page parameter from the $request for pagination purposes
$paged = $request->get_param( \'page\' );
$paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1;
// Get the posts using the \'post\' and \'news\' post types
$posts = get_posts( array(
\'paged\' => $paged,
\'post__not_in\' => get_option( \'sticky_posts\' ),
\'posts_per_page\' => 10,
\'post_type\' => listing,
\'tax_query\' => array(
array (
\'taxonomy\' => \'flux_rss\',
\'field\' => \'slug\',
\'terms\' => \'oui\',
)
),
)
);
// Loop through the posts and push the desired data to the array we\'ve initialized earlier in the form of an object
foreach( $posts as $post ) {
$id = $post->ID;
$post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;
$posts_data[] = (object) array(
\'id\' => $id,
\'title\' => $post->post_title,
\'excerpt\' => wp_json_encode($post->post_excerpt),
\'link\' => $post->guid,
\'featured_img_src\' => $post_thumbnail
);
}
return $posts_data;
}
但是我在响应中得到了一些特殊的字符,因此如何将json响应转换为utf8
[{
"id": 2087,
"title": "Avec l\\u2019ONPA",
"excerpt": "\\"Avec cette association cr\\\\u00e9\\\\u00e9e en 1971, les s\\\\u00e9niors de 55 ans et plus, en activit\\\\u00e9 professionnelle ou non, et vivant \\\\u00e0 domicile, m\\\\u00e8nent une vie active...\\"",
"link": "http:\\/\\/localhost\\/focus\\/?post_type=listing&p=2087",
"featured_img_src": "http:\\/\\/localhost\\/focus\\/wp-content\\/uploads\\/2018\\/05\\/avec-lonpa.jpg"
},
最合适的回答,由SO网友:Tom J Nowell 整理而成
问题在于:
\'excerpt\' => wp_json_encode($post->post_excerpt),
该阵列将通过
wp_json_encode
通过REST API,所以它得到双重编码,所以删除
wp_json_encode
在这里,它会很好地工作,它只是编码,不是人类可读的文本值。
E、 g.将其放在浏览器开发控制台中并输出结果,您将看到这不是问题:
正如你所见,
’
编码为
\\u2019O
因为
20190
是的unicode字符代码
’
, 如果没有某种形式的编码,HTML就不能在本地使用这些字符。这就是为什么当你检查HTML时,你会看到
&
但当您在浏览器中查看时,您会看到
&
, 同样的事情也在这里发生