在wordpress主题中添加自定义文章类型register_post_type和分类教程(WordPress文章类型)。

Wordpress2年前 (2023)发布 SUYEONE
750 0 0

WordPress 是一个功能强大的内容管理系统(CMS),因其易用性和可扩展性而深受网站管理员喜爱。其中一个实用特性是支持自定义文章类型和分类,这使得网站构建更加灵活。在这篇文章中,我们将简要介绍如何在你的主题中添加自定义文章类型 `register_post_type` 和分类 `register_taxonomy`。

1. 添加自定义文章类型

“`php
/* 注册自定义帖子类型 */
add_Action( ‘init’, ‘create_products_post_type’ );
function create_products_post_type() {
$labels = array(
‘name’ => __(‘Product’, ‘wpgp’),
‘singular_name’ => __(‘Product’, ‘wpgp’),
// … 其他标签
);

$args = array(
‘labels’ => $labels,
‘show_ui’ => true, // 是否显示在后台
‘query_var’ => true,
‘show_in_nav_menus’ => false,
‘public’ => true, // 对用户和作者可见
‘hierarchical’ => false,
‘menu_icon’ => ‘dashicons-format-gallery’,
‘has_archive’ => true, // 启用存档
‘rewrite’ => array(‘slug’ => ‘products’),
‘supports’ => array(‘title’, ‘eDiTor’, ‘thumbnAIl’, ‘excerpt’, ‘comments’, ‘custom-fields’, ‘page-attributes’),
‘can_export’ => true,
);

register_post_type( ‘products’, $args );
}
“`

2. 添加分类功能

“`php
/* 为帖子类型“products”注册分类 */
add_action( ‘init’, ‘register_products_taxonomy’ );
function register_products_taxonomy() {
$labels = array(
‘name’ => __(‘Product Categories’, ‘wpgp’),
‘singular_name’ => __(‘Product Category’, ‘wpgp’),
// … 其他标签
);

$args = array(
‘hierarchical’ => true,
‘labels’ => $labels,
‘show_ui’ => true,
‘show_in_menu’ => true,
‘show_in_nav_menus’ => true,
‘query_var’ => true,
‘has_archive’ => false,
‘show_admin_column’ => true,
‘rewrite’ => array(‘slug’ => ‘product’),
);

register_taxonomy( ‘product’, ‘products’, $args );
}
“`

3. 在后台添加自定义文章排序功能

“`php
// 管理页面产品按日期排序
add_filter( ‘parse_query’, ‘sort_products_by_date’ );
function sort_products_by_date() {
global $pagenow;
if (is_admin() && $pagenow == ‘edit.php’ && !empty($_GET[‘post_type’]) && $_GET[‘post_type’] == ‘products’ && !isset($_GET[‘post_status’]) && !isset($_GET[‘orderby’])) {
wp_redirect(admin_url(‘edit.php?post_type=products&orderby=date&order=desc’));
exit();
}
}
“`
以上代码将创建一个名为 “products” 的自定义文章类型,以及一个名为 “product” 的分类。同时,它还会在后台编辑页面中默认按照发布日期降序排列这些产品。请确保将 ‘wpgp’ 替换为你自己的文本域名称。

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!