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

如何为WordPress文章标题添加序号

给博客文章标题添加自动序号的解决方案

针对你使用Gutenberg编辑器和Twenty Twenty-Four主题的场景,提供三种可行方案:

方案一:CSS计数器(零代码,快速实现)

适合不需要全局连续计数(分页后每页从1开始)的场景,操作步骤:

  • 进入WordPress后台,依次点击「外观」→「自定义」→「额外CSS」
  • 粘贴以下代码并保存:
/* 博客列表页标题序号 */
.blog .wp-block-post-template {
  counter-reset: post-counter;
}

.blog .wp-block-post-template > li {
  counter-increment: post-counter;
}

.blog .wp-block-post-title::before {
  content: counter(post-counter) ". ";
  font-weight: bold;
}

/* 单篇文章页标题序号(可选) */
.single-post .wp-block-post-title::before {
  content: counter(post-counter) ". ";
  font-weight: bold;
}

方案二:PHP钩子函数(全局连续计数)

如果需要所有文章按发布顺序全局连续编号(跨分页不重置),建议用子主题避免主题更新丢失修改:

  1. 创建并启用Twenty Twenty-Four的子主题
  2. 在子主题的functions.php文件中添加以下代码:
add_filter( 'the_title', 'add_post_number_to_title', 10, 2 );
function add_post_number_to_title( $title, $post_id ) {
    // 仅针对前台的博客文章,后台标题保持不变
    if ( is_admin() || get_post_type( $post_id ) !== 'post' ) {
        return $title;
    }
    
    // 获取所有已发布文章的ID列表(按发布时间正序)
    $all_posts = get_posts( array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'ASC',
        'fields' => 'ids',
        'posts_per_page' => -1
    ) );
    
    // 计算当前文章的序号
    $post_index = array_search( $post_id, $all_posts ) + 1;
    
    // 拼接序号和标题
    return $post_index . '. ' . $title;
}
  • 若要让最新发布的文章为第1号,将代码中的'order' => 'ASC'改为'order' => 'DESC'即可。

方案三:块主题模板编辑(可视化修改)

利用Gutenberg编辑器的模板编辑功能,结合短代码实现:

  1. 先在子主题的functions.php中添加短代码函数:
add_shortcode( 'post_number', 'get_post_number_shortcode' );
function get_post_number_shortcode() {
    global $post;
    $all_posts = get_posts( array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'ASC',
        'fields' => 'ids',
        'posts_per_page' => -1
    ) );
    $post_index = array_search( $post->ID, $all_posts ) + 1;
    return $post_index . '. ';
}
  1. 进入WordPress后台→「外观」→「编辑器」→「模板」,选择要修改的模板(如「文章列表」或「归档」)
  2. 在文章标题块的前方添加一个「短代码」块,输入[post_number]并保存模板,即可在标题前显示序号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:33:23