温馨提示×

WordPress中设置Post Type自定义文章类型的实例教程

小云
99
2023-08-10 11:56:36
栏目: 编程语言

在WordPress中,可以使用register_post_type()函数来创建自定义文章类型。

以下是一个创建自定义文章类型的示例代码:

function create_custom_post_type() {

$args = array(

‘labels’ => array(

‘name’ => ‘Custom Posts’,

‘singular_name’ => ‘Custom Post’,

),

‘public’ => true,

‘has_archive’ => true,

‘rewrite’ => array(‘slug’ => ‘custom-posts’),

);

register_post_type(‘custom_post’, $args);

}

add_action(‘init’, ‘create_custom_post_type’);

在这个示例中,我们创建了一个名为’Custom Posts’的自定义文章类型,并将其包含的文章称为’Custom Post’。

参数’public’设置为true,表示这个自定义文章类型可以在前台显示。

参数’has_archive’设置为true,表示可以为这个自定义文章类型创建一个归档页面。

参数’rewrite’设置了自定义文章类型的URL重写规则,我们将其slug设置为’custom-posts’,这样文章的URL将会是example.com/custom-posts/post-slug。

最后,我们使用add_action()函数将create_custom_post_type函数与init钩子关联起来,以确保在WordPress初始化时创建自定义文章类型。

要使用这个示例,只需将以上代码添加到你的主题的functions.php文件中即可。然后,你就可以在WordPress后台的文章菜单下看到一个新的’Custom Posts’选项。

0