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

WordPress PHP实现轮播首项标题为H1,其余项为H2

Solution for WordPress Slider Heading Tag Differentiation

Hey there! Since you're new to PHP and WordPress, let's break this down simply. The core idea is to add a counter to track which slide we're on, then use that counter to decide whether to output an <h1> or <h2> tag for the heading.

Here's the modified code with clear explanations:

Step 1: Initialize a slide counter

First, we'll set up a variable right before the loop starts to keep track of the slide number:

<?php $slide_count = 1; // Start counting from the first slide ?>
<?php while(have_rows('banner_slider')) : the_row();?>

Step 2: Replace the fixed <h1> with conditional logic

Instead of always using <h1> for the heading, we'll check if we're on the first slide. If yes, use <h1>; otherwise, use <h2>:

<?php if ($slide_count === 1) : ?>
    <h1><?php the_sub_field('heading');?></h1>
<?php else : ?>
    <h2><?php the_sub_field('heading');?></h2>
<?php endif; ?>

Step 3: Increment the counter after each slide

At the end of the loop, we'll increase the counter so it correctly tracks the next slide in sequence:

<?php $slide_count++; endwhile;?>

Full Modified Code

<?php $slide_count = 1; // Initialize slide counter ?>
<?php while(have_rows('banner_slider')) : the_row();?>
<div class="sl" >
<div class="header-content relative-block align-center text-center flex-container align-middle" style="background:url('<?php the_sub_field('image');?>') no-repeat">
<div class="row">
<div class="columns">
<div class="header-content-inner relative-block animate-children">
<h3><?php the_sub_field('subheading');?></h3>
<?php if ($slide_count === 1) : ?>
    <h1><?php the_sub_field('heading');?></h1>
<?php else : ?>
    <h2><?php the_sub_field('heading');?></h2>
<?php endif; ?>
<p><?php the_sub_field('description');?></p>
<div class="button-group align-center">
<?php $n = 1; while(have_rows('button_links')) : the_row(); $link_lr = get_sub_field('link');?>
<?php if($n == 2){ $n2 = 'hollow'; }else{ $n2 = ''; }?>
<a class="button <?php echo $n2; ?>" href="<?php echo $link_lr['url']; ?>"><span><?php echo $link_lr['title']; ?></span></a>
<?php $n++; endwhile;?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php $slide_count++; endwhile;?>

This setup ensures your first slide uses an <h1> tag (great for SEO, as you should only have one primary <h1> per page) and the following two slides use <h2> tags exactly as you requested.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:08:13