首页 > 解决方案 > 自定义帖子类型和 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

标签: phpwordpresscustom-post-type

解决方案


我必须做的事情,不是在我注册帖子类型时让它“稳定”,而是我后来做了。

像这样。

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但我不确定。


推荐阅读