You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在「文章页面(Posts page)」设置下添加多个自定义文章类型?

实现自定义文章类型独立页面展示的方法

你可以通过以下两种方式,分别展示resources和jobs这两个自定义文章类型的内容:

方法一:使用自定义页面模板

  1. 进入主题文件夹,新建两个模板文件:page-resources.php和page-jobs.php
  2. 在每个文件开头添加模板标识,以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后台,创建两个新页面(比如命名为「资源库」「职位列表」),在页面属性的「模板」选项中选择对应的模板,发布后就能展示对应自定义文章类型的内容。

方法二:使用短代码快速实现

如果不想修改主题文件,可以通过添加短代码功能实现:

  1. 打开主题的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');
  1. 后台创建两个页面,在「资源库」页面添加短代码[display_custom_posts type="resources"],在「职位列表」页面添加[display_custom_posts type="jobs"],发布后即可展示对应内容。

注意:如果你的自定义文章类型在注册时未设置publicly_queryable为true,需要先调整注册代码将该参数设为true,否则无法正常查询展示内容。

内容的提问来源于stack exchange,提问作者Lauren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:33:29