也想出现在这里?联系我们

WordPress创建post type自定义文章类型时添加rest api支持

2024.03.02 wordpress教程
  • 文章介绍
  • 升级版本
  • 评价&建议

要在WordPress中为自定义文章类型添加REST API支持,您需要使用register_post_type()函数时设置show_in_rest参数为true。以下是一些示例代码,说明如何创建一个自定义文章类型并为其添加REST API支持:

function custom_post_type() {
    $labels = array(
        'name'               => 'Custom Posts',
        'singular_name'      => 'Custom Post',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Custom Post',
        'edit_item'          => 'Edit Custom Post',
        'new_item'           => 'New Custom Post',
        'all_items'          => 'All Custom Posts',
        'view_item'          => 'View Custom Post',
        'search_items'       => 'Search Custom Posts',
        'not_found'          => 'No Custom Posts found',
        'not_found_in_trash' => 'No Custom Posts found in Trash',
        'menu_name'          => 'Custom Posts'
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'custompost' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
        'show_in_rest'       => true, // 启用 REST API 支持
    );

    register_post_type( 'custom_post', $args );
}

add_action( 'init', 'custom_post_type' );

上述代码创建了一个名为“Custom Posts”的自定义文章类型,并启用了REST API支持。您可以根据需要调整参数,以满足您的项目要求。

一旦您启用了REST API支持,您就可以使用REST API来访问和操作自定义文章类型的内容。默认情况下,您可以在/wpjson/wp/v2/custom_post端点下找到自定义文章类型的REST API。例如,要获取自定义文章类型的所有文章,您可以访问/wpjson/wp/v2/custom_post

有用0
  • 2024.03.02初次和大家见面了!

等待您对该主题的建议

发表评论

还能输入240个字

Hi, 欢迎加入Wordpress技术交流群,带你装逼带你飞!

我要入群
也想出现在这里?联系我们
wordpress加速

我来推荐一个更牛逼的给你看看?

  • 猛戳我吧