如何将已创建的Custom Post Type分配到不同页面?
必须可以!根本不用费劲儿新建6种自定义文章类型,用自定义分类或者自定义字段就能完美解决你的需求,下面给你两种实操性很强的方案:
方案一:利用自定义分类(Custom Taxonomy)
这是最直观的方法——给你现有的自定义文章类型(CPT)添加一个专属分类,比如叫「页面分组」,然后把CPT文章分配到对应的分组里,最后在每个展示页面调用对应分组的内容即可。
步骤1:注册自定义分类(如果还没的话)
把这段代码加到主题的functions.php文件里,记得把your_custom_post_type替换成你实际的CPT名称:
function register_page_group_taxonomy() { $args = array( 'labels' => array( 'name' => '页面分组', 'singular_name' => '页面分组', 'search_items' => '搜索页面分组', 'all_items' => '所有页面分组', 'edit_item' => '编辑页面分组', 'update_item' => '更新页面分组', 'add_new_item' => '添加新页面分组', 'new_item_name' => '新页面分组名称', 'menu_name' => '页面分组' ), 'hierarchical' => true, // 支持层级,和默认分类一样 'show_ui' => true, 'show_admin_column' => true, // 在CPT列表页显示分类列 'query_var' => true, 'rewrite' => array( 'slug' => 'page-group' ), ); register_taxonomy( 'page_group', 'your_custom_post_type', $args ); } add_action( 'init', 'register_page_group_taxonomy' );
步骤2:给CPT文章分配分组
刷新后台后,编辑你的CPT文章时,侧边栏会出现「页面分组」的选项,直接给文章分配对应的分组(比如「页面A」「页面B」等)就行。
步骤3:在页面中调用对应分组的CPT内容
你可以创建一个自定义页面模板(比如page-cpt-display.php),然后在模板里用WP_Query查询指定分组的内容:
<?php // 假设你给当前页面加了个自定义字段`target_group`,用来存要展示的分组slug $target_group_slug = get_post_meta( get_the_ID(), 'target_group', true ); $args = array( 'post_type' => 'your_custom_post_type', 'posts_per_page' => -1, // 显示所有该分组的文章 'tax_query' => array( array( 'taxonomy' => 'page_group', 'field' => 'slug', 'terms' => $target_group_slug, ), ), ); $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); // 输出你的CPT内容,比如标题、缩略图、摘要等 the_title( '<h3 class="cpt-title">', '</h3>' ); the_excerpt(); endwhile; wp_reset_postdata(); // 重置查询 else : echo '<p>暂无相关内容</p>'; endif; ?>
之后给每个展示页面选择这个模板,再在页面的自定义字段里填入对应的分组slug即可。
方案二:利用自定义字段(Custom Field)
如果不想用分类,也可以直接给每个CPT文章加一个自定义字段,标记它要展示的目标页面,然后在页面中查询匹配该字段的CPT内容。
步骤1:给CPT文章添加自定义字段
编辑CPT文章时,在「自定义字段」面板(如果没显示就去顶部的「屏幕选项」里勾选)添加一个字段:
- 键(Key):
target_page - 值(Value):填入目标页面的ID(比如
123)或者页面slug(比如page-a)
步骤2:在页面中查询匹配的CPT内容
同样可以用自定义页面模板,或者写个短代码更灵活。比如短代码版本:
function cpt_by_target_page_shortcode( $atts ) { // 设置默认参数 $atts = shortcode_atts( array( 'page_id' => get_the_ID(), // 默认匹配当前页面ID 'cpt' => 'your_custom_post_type' ), $atts ); $args = array( 'post_type' => $atts['cpt'], 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'target_page', 'value' => $atts['page_id'], 'compare' => '=' ) ) ); $query = new WP_Query( $args ); $output = ''; if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $output .= '<div class="cpt-item">'; $output .= '<h3>' . get_the_title() . '</h3>'; $output .= '<div>' . get_the_content() . '</div>'; $output .= '</div>'; endwhile; wp_reset_postdata(); else : $output .= '<p>暂无相关内容</p>'; endif; return $output; } add_shortcode( 'show_cpt_for_page', 'cpt_by_target_page_shortcode' );
之后在展示页面里直接插入短代码就行:
- 显示当前页面对应的CPT:
[show_cpt_for_page] - 指定页面ID:
[show_cpt_for_page page_id="123"]
两种方法都能帮你复用现有CPT,不用重新创建内容,按需选就行~
内容的提问来源于stack exchange,提问作者Sergi
相关产品推荐
相关产品推荐

