我能够使用WordPress的重写规则API创建json端点。
方法如下:
// Add custom rewrite rule
function test_rewrite_rule() {
add_rewrite_tag( \'%movies%\', \'([^&]+)\' );
add_rewrite_rule( \'movie-api/([^&]+)/?\', \'index.php?movies=$matches[1]\', \'top\' );
}
add_action( \'init\', \'test_rewrite_rule\' );
// outputting the data
function test_movie_endpoint_data() {
global $wp_query;
$movie_tag = $wp_query->get( \'movies\' );
if ( ! $movie_tag ) {
return;
}
if ( $movie_tag == \'all\' ) {
$movie_tag = false;
}
$movie_data = array();
$args = array(
\'post_type\' => \'movies\',
\'posts_per_page\' => 100,
\'moxie_tag\' => esc_attr( $movie_tag ),
);
$movie_query = new WP_Query( $args );
if ( $movie_query->have_posts() ) : while ( $movie_query->have_posts() ) :
$movie_query->the_post();
$movie_data[] = array(
\'id\' => get_the_id(),
\'title\' => get_the_title(),
\'poster_url\' => esc_url( test_get_meta(\'poster_url\') ),
\'rating\' => test_get_meta(\'rating\'),
\'year\' => test_get_meta(\'year\'),
\'short_description\' => test_get_meta(\'description\'),
);
endwhile;
wp_reset_postdata();
endif;
wp_send_json( $movie_data );
}
add_action( \'template_redirect\', \'test_movie_endpoint_data\' );
但是,当我尝试使用wordpress的wp\\u remote\\u get()、curl或file\\u get\\u contents()提取json数据时,它返回NULL。
知道从终点获取前端信息的最佳方法是什么吗?