首页 视频课程 主题开发课程第14章、文章类型 WordPress注册自定义文章类型

WordPress注册自定义文章类型

2023-06-11 / 353阅

WordPress注册自定义文章类型

在 WordPress 中,除了默认的文章和页面类型之外,您还可以注册自己定义的自定义文章类型。本文将为您提供一个使用简单的代码示例来注册一个自定义文章类型。

首先,在您的主题的 functions.php 文件中添加以下代码:

function custom_post_type() {

    // 定义自定义文章类型的标签
    $labels = array(
        'name'               => _x( 'Books', 'post type 名称', 'text-domain' ),
        'singular_name'      => _x( 'Book', 'post type 单个名称', 'text-domain' ),
        'menu_name'          => _x( 'Books', 'admin menu', 'text-domain' ),
        'name_admin_bar'     => _x( 'Book', 'add new on admin bar', 'text-domain' ),
        'add_new'            => _x( 'Add New', 'book', 'text-domain' ),
        'add_new_item'       => __( '添加新书籍', 'text-domain' ),
        'new_item'           => __( '新书籍', 'text-domain' ),
        'edit_item'          => __( '编辑书籍', 'text-domain' ),
        'view_item'          => __( '查看书籍', 'text-domain' ),
        'all_items'          => __( '所有书籍', 'text-domain' ),
        'search_items'       => __( '搜索书籍', 'text-domain' ),
        'parent_item_colon'  => __( 'Parent Books:', 'text-domain' ),
        'not_found'          => __( 'No books found.', 'text-domain' ),
        'not_found_in_trash' => __( 'No books found in Trash.', 'text-domain' )
    );

    // 定义自定义文章类型的选项
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'book' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
    );

    // 注册自定义文章类型
    register_post_type( 'book', $args );

}
add_action( 'init', 'custom_post_type' ); 

在上面的代码中,我们首先定义了自定义文章类型的标签,包括名称、单个名称、菜单名称等。然后定义了自定义文章类型的选项,包括公开显示、显示在菜单中、支持的字段等。最后我们使用 register_post_type() 函数将自定义文章类型注册到 WordPress 中。

现在您可以在 WordPress 后台中看到一个名为 Books 的新菜单项,并且您可以创建和管理新的 Book 类型的文章了。

希望这个代码示例对您有所帮助,您可以根据自己的需要进行修改和扩展。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录