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

WordPress能否创建多个文章页面?实现内容差异化样式与自定义URL

在WordPress中创建带自定义样式的多类型文章页面

实现思路

通过自定义文章类型(CPT) + 自定义模板组合,实现不同内容类别的独立列表页、单页,同时自定义URL结构和专属样式。


步骤1:注册自定义文章类型

在主题的functions.php文件中添加以下代码,分别注册三类内容的自定义文章类型:

// 注册「随笔&文章」类型
function register_essay_articles_cpt() {
    $args = array(
        'public' => true,
        'label'  => '随笔&文章',
        'rewrite' => array( 'slug' => 'essay-&-articles' ), // 对应列表页URL
        'has_archive' => true, // 启用归档列表页
        'supports' => array( 'title', 'editor', 'thumbnail' )
    );
    register_post_type( 'essay_articles', $args );
}
add_action( 'init', 'register_essay_articles_cpt' );

// 注册「书籍」类型
function register_books_cpt() {
    $args = array(
        'public' => true,
        'label'  => '书籍',
        'rewrite' => array( 'slug' => 'books' ),
        'has_archive' => true,
        'supports' => array( 'title', 'editor', 'thumbnail' )
    );
    register_post_type( 'books', $args );
}
add_action( 'init', 'register_books_cpt' );

// 注册「美食」类型
function register_foods_cpt() {
    $args = array(
        'public' => true,
        'label'  => '美食',
        'rewrite' => array( 'slug' => 'foods' ),
        'has_archive' => true,
        'supports' => array( 'title', 'editor', 'thumbnail' )
    );
    register_post_type( 'foods', $args );
}
add_action( 'init', 'register_foods_cpt' );

添加完成后,进入后台「设置→固定链接」页面,点击一次保存按钮刷新重写规则,确保URL结构生效。


步骤2:创建自定义模板(实现差异化样式)

在主题文件夹下创建对应模板文件,分别控制每个类型的列表页和单页样式:

1. 列表页模板

  • 「随笔&文章」列表页:创建archive-essay_articles.php,复制主题默认archive.php的内容,修改HTML结构或添加专属CSS类;
  • 「书籍」列表页:创建archive-books.php;
  • 「美食」列表页:创建archive-foods.php。

这些模板会自动匹配到/essay-&-articles、/books、/foods页面,你可以完全自定义页面布局和样式。

2. 单页模板

  • 「随笔&文章」单页:创建single-essay_articles.php,基于主题默认single.php修改;
  • 「书籍」单页:创建single-books.php;
  • 「美食」单页:创建single-foods.php。

这些模板会自动对应到/essay-&-articles/文章ID或别名、/books/文章ID或别名这类单页URL,实现不同内容类型的单页样式差异化。


补充:强制用ID作为单页URL后缀

如果需要单页URL为/essay-&-articles/1这种ID形式,添加以下代码调整 permalink 规则:

function custom_cpt_permalink( $post_link, $post ) {
    if ( 'essay_articles' === $post->post_type && 'publish' === $post->post_status ) {
        $post_link = home_url( '/essay-&-articles/' . $post->ID . '/' );
    }
    if ( 'books' === $post->post_type && 'publish' === $post->post_status ) {
        $post_link = home_url( '/books/' . $post->ID . '/' );
    }
    if ( 'foods' === $post->post_type && 'publish' === $post->post_status ) {
        $post_link = home_url( '/foods/' . $post->ID . '/' );
    }
    return $post_link;
}
add_filter( 'post_type_link', 'custom_cpt_permalink', 10, 2 );

修改后再次进入「固定链接」页面保存刷新规则即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:16:05