如何在「文章页面(Posts page)」设置下添加多个自定义文章类型?
实现自定义文章类型独立页面展示的方法
你可以通过以下两种方式,分别展示resources和jobs这两个自定义文章类型的内容:
方法一:使用自定义页面模板
- 进入主题文件夹,新建两个模板文件:
page-resources.php和page-jobs.php - 在每个文件开头添加模板标识,以
page-resources.php为例:
<?php /* Template Name: 资源页面专用模板 */ get_header(); ?>
page-jobs.php对应修改标识为「职位页面专用模板」即可。
3. 在模板的内容区域替换默认查询,写入自定义文章类型的查询代码:
<?php // 查询resources类型的所有文章 $args = array( 'post_type' => 'resources', 'posts_per_page' => -1, // 显示全部内容,可改为具体数字限制数量 'orderby' => 'date', 'order' => 'DESC' ); $custom_query = new WP_Query($args); if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post(); // 这里写入文章内容输出逻辑,示例如下 the_title('<h2 class="post-title">', '</h2>'); the_excerpt(); echo '<a href="'.get_permalink().'" class="read-more">查看详情</a>'; endwhile; wp_reset_postdata(); // 重置查询,避免影响后续内容 else : echo '<p>暂无资源类文章</p>'; endif; ?>
page-jobs.php只需将post_type的值改为jobs即可。
4. 回到WordPress后台,创建两个新页面(比如命名为「资源库」「职位列表」),在页面属性的「模板」选项中选择对应的模板,发布后就能展示对应自定义文章类型的内容。
方法二:使用短代码快速实现
如果不想修改主题文件,可以通过添加短代码功能实现:
- 打开主题的
functions.php文件,添加以下代码:
// 自定义文章类型展示短代码 function show_custom_posts($atts) { $params = shortcode_atts(array( 'type' => 'post', 'count' => -1 ), $atts); $query_args = array( 'post_type' => $params['type'], 'posts_per_page' => $params['count'], 'orderby' => 'date', 'order' => 'DESC' ); $custom_query = new WP_Query($query_args); $content = ''; if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post(); $content .= '<div class="custom-post-item">'; $content .= '<h3>'.get_the_title().'</h3>'; $content .= '<p>'.get_the_excerpt().'</p>'; $content .= '<a href="'.get_permalink().'">点击查看</a>'; $content .= '</div>'; endwhile; wp_reset_postdata(); else : $content .= '<p>暂无相关内容</p>'; endif; return $content; } add_shortcode('display_custom_posts', 'show_custom_posts');
- 后台创建两个页面,在「资源库」页面添加短代码
[display_custom_posts type="resources"],在「职位列表」页面添加[display_custom_posts type="jobs"],发布后即可展示对应内容。
注意:如果你的自定义文章类型在注册时未设置publicly_queryable为true,需要先调整注册代码将该参数设为true,否则无法正常查询展示内容。
内容的提问来源于stack exchange,提问作者Lauren
相关产品推荐
相关产品推荐

