我有他的自定义帖子类型
function wp_post_types() {
// Nicknames post type
register_post_type('subscription', array(
'supports' => array('title'),
'public' => true,
'show_ui' => true,
'labels' => array(
'name' => 'Subscription',
'add_new_item' => 'Add New Subscription',
'edit_item' => 'Edit Subscriptions',
'all_items' => 'All Subscriptions',
'singular_name' => 'Subscription'
),
'menu_icon' => 'dashicons-universal-access-alt'
));
}
add_action('init', 'wp_post_types');
这是我在function.php中的代码,用于注册自定义REST API
add_action('rest_api_init', 'searchSubscription');
function searchSubscription() {
register_rest_route('CustomAPI/v3', 'search', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'getSubscription'
));
}
function getSubscription() {
$subscriptions = new WP_Query(array(
'perm' => 'readable',
'post_type' => 'subscription',
'posts_per_page' => '5'
));
$subscriptionResults = array();
while($subscriptions->have_posts()) {
$subscriptions->the_post();
array_push($subscriptionResults, array(
'title' => get_the_title(),
'region' => get_field('regi'),
'country' => get_field('country'),
'activity' => get_field('activity'),
'time' => get_field('time')
));
}
return $subscriptionResults;
}
问题:对于未登录的用户,它不显示任何结果。错误:
{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}
适用于管理员用户。我可以看到来自http://localhost/wp-json/CustomAPI/v1/subscription/
的json数据[{"title":"Matt","region":"Central Visayas","country":"PH","activity":"2 months premium membership","time":"2018-01-31 06:36:53"},{"title":"Johnmark","region":"Central Visayas","country":"PH","activity":"Life time membership","time":"2018-01-31 06:29:52"}]
任何想法我的代码有什么问题,为什么它没有显示未登录的用户?
答案 0 :(得分:1)
将“show_in_rest”参数添加到register_post_type()
功能。
function wp_post_types() {
// Nicknames post type
register_post_type('subscription', array(
'supports' => array('title'),
'public' => true,
'show_ui' => true,
'show_in_rest' => true,
'labels' => array(
'name' => 'Subscription',
'add_new_item' => 'Add New Subscription',
'edit_item' => 'Edit Subscriptions',
'all_items' => 'All Subscriptions',
'singular_name' => 'Subscription'
),
'menu_icon' => 'dashicons-universal-access-alt'
));
}
add_action('init', 'wp_post_types');
答案 1 :(得分:0)
试试此代码
add_action('rest_api_init', 'searchSubscription');
function searchSubscription() {
register_rest_route('CustomAPI/v1', 'subscription', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'getSubscription'
));
}
function getSubscription() {
$subscriptions = new WP_Query(array(
'perm' => 'readable',
'post_type' => 'subscription',
'posts_per_page' => '5'
));
$subscriptionResults = array();
while($subscriptions->have_posts()) {
$subscriptions->the_post();
array_push($subscriptionResults, array(
'title' => get_the_title(),
'region' => get_field('regi'),
'country' => get_field('country'),
'activity' => get_field('activity'),
'time' => get_field('time')
));
}
return $subscriptionResults;
}
答案 2 :(得分:0)
尝试删除'perm'参数。