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

求助:用jQuery实现WordPress当前文章标题居中并添加类

搞定WordPress分类文章列表:当前标题居中+高亮

嘿,我来帮你完善代码,实现你要的两个核心需求——展示分类ID12的所有文章标题,同时让当前页面的标题自动居中并带上专属样式。

1. 完整的PHP模板代码

先把你的代码补全并优化,加入当前文章的判断逻辑,这样就能给对应标题添加专属类了:

<div class="opacity cat">
  <div class="inner-home">
    <?php 
    // 初始化查询:拉取分类ID12的所有文章(posts_per_page=-1表示显示全部)
    $category_query = new WP_Query( array(
      'cat' => 12,
      'posts_per_page' => -1,
      'orderby' => 'title', // 可选:按标题排序,也可以换成date按发布时间排
      'order' => 'ASC'
    ) );
    // 获取当前页面的文章ID(仅在单文章页面时这个值有效)
    $current_post_id = get_the_ID();
    ?>

    <!-- 显示分类名称,用esc_html转义更安全 -->
    <p><?php echo esc_html( get_cat_name(12) ); ?></p>

    <!-- 文章标题列表 -->
    <ul class="category-posts-list">
      <?php if ( $category_query->have_posts() ) : ?>
        <?php while ( $category_query->have_posts() ) : $category_query->the_post(); ?>
          <!-- 判断当前循环的文章是不是页面正在展示的文章,是的话加current-post类 -->
          <li class="<?php echo get_the_ID() === $current_post_id ? 'current-post' : ''; ?>">
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
          </li>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); // 必须加!重置查询,避免影响后续的WP函数 ?>
      <?php else : ?>
        <li><?php esc_html_e( '这个分类还没文章哦', '你的主题文本域' ); ?></li>
      <?php endif; ?>
    </ul>
  </div>
</div>

2. CSS样式:高亮当前标题+调整布局

把下面的CSS加到你主题的style.css或者自定义CSS面板里,给当前标题加特殊样式,同时优化列表布局:

/* 重置列表默认样式 */
.category-posts-list {
  list-style: none;
  padding: 0;
  margin: 2rem 0;
  /* 垂直排列标题,要水平排就把flex-direction改成row */
  display: flex;
  flex-direction: column;
  gap: 1rem; /* 标题之间留些间距 */
}

/* 当前文章标题的专属样式,你可以随便改颜色、背景 */
.category-posts-list .current-post {
  font-weight: bold;
  color: #1a73e8; /* 高亮蓝色,换成你喜欢的颜色 */
  padding: 0.5rem 1rem;
  background-color: rgba(26, 115, 232, 0.1); /* 淡蓝色背景,更突出 */
}

3. 页面加载时自动滚动到当前标题(可选)

如果你想要页面一加载,当前标题就自动滚到浏览器视口中间,加这段JS代码到主题的functions.php(通过wp_enqueue_script引入)或者直接放在模板底部:

document.addEventListener('DOMContentLoaded', function() {
  const currentPost = document.querySelector('.category-posts-list .current-post');
  if (currentPost) {
    // 平滑滚动到元素,让它在视口垂直居中
    currentPost.scrollIntoView({
      behavior: 'smooth', // 平滑滚动,去掉就是瞬间跳转
      block: 'center'
    });
  }
});

几个重要的小提醒

  • wp_reset_postdata():这个一定要加,不然之后用the_post()之类的WP函数会出问题,相当于重置查询环境。
  • esc_html():用来转义输出的内容,防止安全问题,这是WordPress开发的好习惯哦。
  • 排序可以改:如果不想按标题排序,把orderby改成date,order改成DESC就是按最新发布的文章排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:36:36