[英]Custom Post Type and API REST is not working
I have been created a custom post type called 'customers'. 我已经创建了一个称为“客户”的自定义帖子类型。 I'm registering step by step as documentation says. 我正在按文档所述逐步进行注册。 But when I call to rest api, It just return a 404 response. 但是当我调用rest api时,它只返回404响应。 See the code below: 请参见下面的代码:
add_action('init', 'customer_post_type');
function customer_post_type() {
$labels = array(
'name' => _x('Customers', 'customers'),
'singular_name' => _x('Customer', 'customers'),
'menu_name' => __('Customers', 'customers'),
'parent_item_colon' => __('Parent Customer', 'customers'),
'all_items' => __('All Customers', 'customers'),
'view_item' => __('View Customer', 'customers'),
'add_new_item' => __('Add New Customer', 'customers'),
'add_new' => __('Add New', 'customers'),
'edit_item' => __('Edit Customer', 'customers'),
'update_item' => __('Update Customer', 'customers'),
'search_items' => __('Search Customer', 'customers'),
'not_found' => __('Not Found', 'customers'),
'not_found_in_trash' => __('Not found in Trash', 'customers'),
);
$args = array(
'label' => __('Customers', 'customers'),
'description' => __('Customer news and reviews', 'customers'),
'labels' => $labels,
'supports' => array('title', 'author', 'thumbnail', 'custom-fields', ),
'hierarchical' => false,
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'menu_icon' => 'dashicons-desktop',
'show_in_rest' => true,
'rest_base' => 'customer',
'rest_controller_class' => 'WP_REST_Post_Controller'
);
register_post_type('customers', $args);
}
the urls that I testing for, are: /wp-json/wp/v2/customers
and /wp-json/wp/v2/customer
我测试的网址是: /wp-json/wp/v2/customers
和/wp-json/wp/v2/customer
Something I had to do, was instead of making it "restable" when i register the post type, I did it later. 我要做的是,当我注册帖子类型时,不是让它“静止”,而是后来。
like this. 像这样。
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
//be sure to set this to the name of your post type!
$post_type_name_customers = 'customer';
if( isset( $wp_post_types[ $post_type_name_customers ] ) ) {
$wp_post_types[$post_type_name_customers]->show_in_rest = true;
$wp_post_types[$post_type_name_customers]->rest_base = $post_type_name_customers;
$wp_post_types[$post_type_name_customers]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
Like this, I was able to get my CPT through rest. 这样,我就可以通过休息获得CPT。
You could try it out - 您可以尝试一下-
Remember to remove them from the registration of the post form. 请记住将其从邮寄表格的注册中删除。
Also, you might have to set "public" => true
But i am not sure. 另外,您可能必须设置"public" => true
但是我不确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.