WordPress 提供两种内置内容类型:文章(用于博客文章)和页面(用于静态页面)。但许多网站需要管理根本不同的内容类型——产品、投资组合、事件、推荐或食谱。这正是自定义文章类型的用途。
本指南解释什么是自定义文章类型、为什么应该使用它们,以及如何使用无代码插件 (CPT UI) 和 PHP 代码创建它们。
1. 什么是自定义文章类型?
自定义文章类型 (CPT) 是您在 WordPress 中创建的超越内置 Post 和 Page 类型的内容类型。将其视为向 WordPress 管理员添加新"抽屉"以组织特定类型的结构化内容。
常见的自定义文章类型示例:
- 产品 — 不使用 WooCommerce 的电子商务网站
- 投资组合 — 展示代理商或自由职业者的工作
- 推荐 — 客户评论和推荐
- 食谱 — 包含成分、说明和营养的食谱
- 事件 — 带有日期、时间和地点详情的事件
- 员工 / 团队 — 带有职位和社交链接的团队资料
2. CPT 与文章和页面的区别
| 类型 | 用于 | 有分类/标签? | 排序方式 |
|---|---|---|---|
| 文章 | 博客文章、新闻 | 是 | 日期 |
| 页面 | 永久页面(关于、联系) | 否 | 层级(父/子) |
| 自定义文章类型 | 专业化内容 — 可配置 | 可配置 | 可配置 |
CPT 的强大之处在于您可以精确选择它们拥有的功能——分类、标签、特色图像、自定义字段、摘要——使您的内容比使用通用文章更有条理和结构。
3. 使用插件创建 CPT — 自定义文章类型 UI
CPT UI 是最用户友好的免费插件,用于创建无需任何编码的自定义文章类型。
安装和使用 CPT UI
- 转到插件 → 添加新插件,搜索"自定义文章类型 UI",安装并激活
- 导航到CPT UI → 添加/编辑文章类型
- 输入文章类型别名(例如
portfolio)— 小写,无空格 - 输入复数标签(例如"投资组合")和单数标签(例如"投资组合项目")
- 在支持中,根据需要选择:标题、编辑器、缩略图、摘要
- 如果需要列表页面(例如
/portfolio/),将有归档设置为真 - 单击添加文章类型 — 完成!
"投资组合"菜单项现在将出现在 WordPress 管理侧栏中,您可以立即开始添加条目。
提示:CPT UI 还允许您创建自定义分类法——特定于您的 CPT 的类别类分组。例如,创建与标准文章分类分开的"投资组合分类"。转到CPT UI → 添加/编辑分类法。
4. 使用代码创建 CPT — register_post_type()
基于代码的方法为开发人员提供了完整的灵活性,无需依赖插件。仅将其添加到您的子主题的 functions.php 文件中。
/**
* Register Custom Post Type: Portfolio
*/
function asiagb_register_portfolio() {
$labels = array(
'name' => 'Portfolio',
'singular_name' => 'Portfolio Item',
'add_new' => 'Add New',
'add_new_item' => 'Add New Portfolio Item',
'edit_item' => 'Edit Portfolio Item',
'all_items' => 'All Portfolio Items',
'menu_name' => 'Portfolio',
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'portfolio' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 5,
'menu_icon' => 'dashicons-images-alt2',
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
'show_in_rest' => true, // Required for Gutenberg Block Editor
);
register_post_type( 'portfolio', $args );
}
add_action( 'init', 'asiagb_register_portfolio' );
重要:只编辑子主题的 functions.php — 永远不要编辑父主题。对父主题的更改会在主题更新时被覆盖。如果您还没有子主题,请先创建一个。
5. 使用 ACF 添加自定义字段
默认情况下,自定义文章类型仅支持标题、编辑器内容和特色图像。对于专业化的字段——价格、项目 URL、事件日期或成分列表——使用ACF(高级自定义字段)。
使用 ACF 添加自定义字段
- 从 WordPress.org 安装免费的高级自定义字段插件
- 转到自定义字段 → 新增
- 命名字段组(例如"投资组合详情")
- 单击添加字段并选择字段类型:
文本— 用于短文本,如客户名称URL— 用于实时项目链接图像— 用于其他库图像日期选择器— 用于项目完成日期选择— 用于下拉列表分类
- 在位置规则中,设置"文章类型"等于"投资组合"
- 单击发布 — 字段会立即出现在投资组合编辑器中
6. 使用 WP_Query 在主题中显示 CPT 内容
注册自定义文章类型后,在模板文件中使用 WP_Query 来获取和显示内容。
<?php
// Fetch the 12 most recent Portfolio items
$portfolio_query = new WP_Query( array(
'post_type' => 'portfolio',
'posts_per_page' => 12,
'orderby' => 'date',
'order' => 'DESC',
) );
if ( $portfolio_query->have_posts() ) :
while ( $portfolio_query->have_posts() ) : $portfolio_query->the_post(); ?>
<article class="portfolio-item">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'medium' ); ?>
<h3><?php the_title(); ?></h3>
</a>
<!-- Display ACF field -->
<p><?php echo get_field( 'client_name' ); ?></p>
</article>
<?php endwhile;
wp_reset_postdata();
else :
echo '<p>No portfolio items found.</p>';
endif; ?>
9. 自定义分类法 — 按您的方式组织 CPT 内容
自定义分类法是您专门为自定义文章类型创建的分类系统——与 WordPress 的内置分类和标签分开。专用分类法为您的结构化内容提供了更清晰的组织层级。示例:
- 投资组合 CPT → 分类法:"项目类型"(网页设计、品牌、摄影)
- 事件 CPT → 分类法:"事件格式"(会议、工作坊、网络研讨会)
- 食谱 CPT → 分类法:"美食"(泰国菜、意大利菜、甜点)
- 员工 CPT → 分类法:"部门"(工程、销售、营销)
在代码中注册自定义分类法
/**
* Register Custom Taxonomy: Project Type for Portfolio
*/
function asiagb_register_portfolio_taxonomy() {
$labels = array(
'name' => 'Project Types',
'singular_name' => 'Project Type',
'all_items' => 'All Project Types',
'edit_item' => 'Edit Project Type',
'add_new_item' => 'Add New Project Type',
);
register_taxonomy(
'portfolio_type', // taxonomy slug
array( 'portfolio' ), // attach to portfolio CPT
array(
'hierarchical' => true, // true = category-like, false = tag-like
'labels' => $labels,
'show_ui' => true,
'show_in_rest' => true,
'rewrite' => array( 'slug' => 'portfolio-type' ),
)
);
}
add_action( 'init', 'asiagb_register_portfolio_taxonomy' );
注意:hierarchical => true 创建具有父/子术语的类别样式分类法。将其设置为 false 会创建标签样式的平面列表。根据内容如何需要被组织来选择。
10. 使用 WP_Query 按分类法过滤 CPT 内容
一旦有了自定义分类法,您可以使用 tax_query 过滤 WP_Query 结果以仅显示特定项目类型的投资组合项目——非常适合构建过滤库页面。
<?php
// Fetch only "Web Design" portfolio items
$args = array(
'post_type' => 'portfolio',
'tax_query' => array(
array(
'taxonomy' => 'portfolio_type',
'field' => 'slug',
'terms' => 'web-design',
),
),
'posts_per_page' => 6,
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
echo '<h3>' . get_the_title() . '</h3>';
echo '<p>' . get_the_excerpt() . '</p>';
endwhile;
wp_reset_postdata();
高级提示:使用 get_terms( 'portfolio_type' ) 检索所有分类术语并构建动态过滤菜单——例如,标记为"全部 | 网页设计 | 品牌 | 摄影"的选项卡——而无需硬编码任何内容。
11. 主题中的自定义文章类型模板文件
WordPress 使用其模板层级自动查找特定于每个自定义文章类型的主题模板文件。您可以在子主题中创建这些文件来完全自定义显示:
| 模板文件 | 用途 | 示例 |
|---|---|---|
single-{post_type}.php |
单个自定义文章类型条目页面 | single-portfolio.php |
archive-{post_type}.php |
归档列表页面 | archive-portfolio.php |
taxonomy-{taxonomy}.php |
分类法术语页面 | taxonomy-portfolio_type.php |
single.php |
当无特定模板时的回退模板 | 当 single-portfolio.php 不存在时使用 |
WordPress 会选择最具体的可用模板。如果 single-portfolio.php 存在,则使用该文件;否则将通过层级回退到 single.php。创建特定于自定义文章类型的模板可让您完全控制设计,而不影响其他内容类型。
7. 注册后刷新固定链接规则
创建新的自定义文章类型后,您必须刷新固定链接规则,以便 WordPress 生成正确的 URL 路由。如果没有此步骤,单篇文章和归档页面将返回 404 错误。
如何刷新固定链接:
- 在 WordPress 后台前往 设置 → 固定链接
- 不做任何修改,直接点击 保存更改
- WordPress 将自动重新生成重写规则
注意:添加新的自定义文章类型时,以及每次激活或停用 CPT UI 插件时,都应刷新固定链接。
8. 将自定义文章类型与 Gutenberg 配合使用
要使自定义文章类型与 Gutenberg 块编辑器兼容,请确认在 register_post_type() 中将 'show_in_rest' => true 设置为 true。
对于 CPT UI:前往 CPT UI → 添加/编辑文章类型,并将 在 REST API 中显示 设置为 True。
此设置还允许该文章类型与 REST API 集成、无头 WordPress 设置以及依赖块编辑器基础架构的现代页面构建器配合使用。
12. Querying CPT Data Through the REST API
Once 'show_in_rest' => true is set, WordPress automatically creates REST API endpoints for your Custom Post Type. This opens the door to headless WordPress setups, mobile apps, and SPAs that consume WordPress content without a traditional theme.
Example endpoints generated automatically for a CPT named portfolio:
# Retrieve all portfolio items (JSON)
GET /wp-json/wp/v2/portfolio
# Retrieve a single portfolio item by ID
GET /wp-json/wp/v2/portfolio/123
# Filter by taxonomy term
GET /wp-json/wp/v2/portfolio?portfolio_type=web-design
# Retrieve with ACF fields (requires ACF + REST API enabled on field group)
GET /wp-json/wp/v2/portfolio?_fields=id,title,acf
Security note: REST API endpoints are public by default. If your CPT contains sensitive data, combine 'public' => false with 'show_in_rest' => true to require authentication for API access while still supporting the block editor.
13. Caching WP_Query Results for Custom Post Types
On high-traffic sites, repeatedly querying the same Custom Post Type can increase database load. WordPress Transients provide a simple built-in caching mechanism that stores query results temporarily, reducing the number of database calls.
Caching With the Transient API
<?php
// Check for cached results first
$portfolio_items = get_transient( 'portfolio_all' );
if ( false === $portfolio_items ) {
$q = new WP_Query( array(
'post_type' => 'portfolio',
'posts_per_page' => 20,
'no_found_rows' => true, // skip SQL_CALC_FOUND_ROWS
'update_post_meta_cache' => true,
) );
$portfolio_items = $q->posts;
// Cache for 1 hour (3600 seconds)
set_transient( 'portfolio_all', $portfolio_items, HOUR_IN_SECONDS );
}
foreach ( $portfolio_items as $post ) {
setup_postdata( $post );
the_title( '<h3>', '</h3>' );
}
wp_reset_postdata();
Always clear the transient cache when portfolio items are added, updated, or deleted by hooking into save_post_portfolio to ensure the front end always shows current data.
Tip: Setting 'no_found_rows' => true skips the SQL_CALC_FOUND_ROWS operation — the slowest part of WP_Query — whenever you don't need pagination count data.
14. Migrating CPT Data Between Environments With WP-CLI
When moving Custom Post Type content from a development environment to production — or creating targeted backups — WP-CLI offers more precision than the standard WordPress import/export tools.
| WP-CLI Command | What It Does |
|---|---|
wp post list --post_type=portfolio |
List all portfolio items with their IDs |
wp export --post_type=portfolio |
Export only portfolio items to an XML file |
wp import portfolio.xml --authors=create |
Import portfolio XML into a new WordPress install |
wp post delete $(wp post list --post_type=portfolio --format=ids) |
Delete all portfolio items in a single command |
WP-CLI runs over SSH, making it ideal for hosting environments with shell access — such as AsiaGB VPS plans that include full root access.
WordPress Hosting That Supports Custom Post Types and ACF
AsiaGB Hosting fully supports WordPress with multiple PHP versions, MySQL databases, and an easy-to-use DirectAdmin control panel. Starting at 500 THB/year.
View Hosting Plans →