php - 自定义帖子类型和 API REST 不起作用
问题描述
我已经创建了一个名为“客户”的自定义帖子类型。正如文档所述,我正在逐步注册。但是当我调用 rest api 时,它只返回一个 404 响应。请看下面的代码:
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);
}
我测试的网址是:/wp-json/wp/v2/customers
和/wp-json/wp/v2/customer
解决方案
我必须做的事情,不是在我注册帖子类型时让它“稳定”,而是我后来做了。
像这样。
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';
}
}
像这样,我能够通过休息得到我的CPT。
你可以试试看——
请记住将它们从帖子表单的注册中删除。
另外,您可能必须设置"public" => true
但我不确定。
推荐阅读
- c++ - 如何在焦点链中添加复选框(QCheckBox)
- node.js - 您如何在 Heroku 应用程序上快速工作?
- sap-successfactors - SuccessFactors 的身份验证并获取所有实体
- rust - 为什么动态闭包(作为特征对象的闭包)在放置 Rc 后变得不可用
>? - xaml - 将第一个元素设置为 x:Null(一个 Xaml 问题)
- python - 如何在 Django 的项目文件夹中创建数据库?
- vue.js - 在 Vue 中过滤嵌套循环
- mysql - SQL - 在 FIND_IN_SET 函数中使用变量时“非法混合排序规则”
- google-apps-script - Google Apps Script TextFinder startFrom 不是从
- sql - 如何在VB中从SQL返回一个数组?