WordPress Rest API通过元数据meta获取文章列表posts
2021-04-06
只需简单两步。
一、WordPress后端配置过滤器
如在functions.php中添加:
if( ! function_exists( 'post_meta_request_params' ) ) :
function post_meta_request_params( $args, $request )
{
$args += array(
'meta_key' => $request['meta_key'],
'meta_value' => $request['meta_value'],
'meta_query' => $request['meta_query'],
);
return $args;
}
add_filter( 'rest_post_query', 'post_meta_request_params', 99, 2 );
// add_filter( 'rest_page_query', 'post_meta_request_params', 99, 2 ); // Add support for `page`
// add_filter( 'rest_my-custom-post_query', 'post_meta_request_params', 99, 2 ); // Add support for `my-custom-post`
endif;
二、前端调用
/wp-json/wp/v2/posts/?meta_key=customxxx&meta_value=helloworld
meta字段参数show_in_rest需要设置为true,详情见:
应用列表不限于post类型,在WordPress中,过滤器rest_{$this->post_type}_query,它允许我们为Rest API添加查询参数支持。
rest_post_query – To filter post type rest API query.
rest_page_query – To filter page type rest API query.
rest_docs_query – To filter docs (custom post type) rest API query.
参考资料:
https://maheshwaghmare.com/search-post-by-post-meta-with-rest-api/
另外,通过多个meta获取post列表,尚未实践,可参考: