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

如何通过PHP的if/elseif/else根据页面ID切换显示不同幻灯片?

解决PHP if/elseif语法混用导致的错误

你遇到的核心问题是混用了PHP条件语句的两种不同语法格式——前面的if用的是替代语法(冒号: + endif;),但elseif却切换成了常规大括号{}写法,这会让PHP解析器无法正确识别代码结构,直接抛出语法错误。另外你原代码里的<header>标签还存在未闭合的语法问题,我一起帮你修正。

正确的替代语法写法(适合HTML/PHP混写场景)

这种写法用冒号结尾每个条件分支,最后用endif;闭合整个条件块,结构更清晰:

<?php if( is_front_page() ) : ?>
    <div class="mobile-header">
        <img src="/images/mobile-header.jpg" width="1080" height="1000" alt="Sean Sheehan" />
    </div>
    <?php if ( function_exists( 'soliloquy' ) ) { soliloquy( 'homepage-dark', 'slug' ); } ?>
<?php elseif ( is_page(25) ) : ?>
    <div class="mobile-header">
        <img src="/images/mobile-header.jpg" width="1080" height="1000" alt="Sean Sheehan" />
    </div>
    <?php if ( function_exists( 'soliloquy' ) ) { soliloquy( 'photography-dark', 'slug' ); } ?>
<?php else : ?>
    <header id="masthead" class="<?php echo is_singular() && twentynineteen_can_show_post_thumbnail() ? 'site-header featured-image' : 'site-header'; ?>">
        <!-- 这里可以添加header区域的其他内容 -->
    </header>
<?php endif; ?>

可选:常规大括号写法

如果你更习惯用大括号包裹条件逻辑,也可以统一用这种格式:

<?php
if( is_front_page() ) {
?>
    <div class="mobile-header">
        <img src="/images/mobile-header.jpg" width="1080" height="1000" alt="Sean Sheehan" />
    </div>
    <?php if ( function_exists( 'soliloquy' ) ) { soliloquy( 'homepage-dark', 'slug' ); } ?>
<?php
} elseif ( is_page(25) ) {
?>
    <div class="mobile-header">
        <img src="/images/mobile-header.jpg" width="1080" height="1000" alt="Sean Sheehan" />
    </div>
    <?php if ( function_exists( 'soliloquy' ) ) { soliloquy( 'photography-dark', 'slug' ); } ?>
<?php
} else {
?>
    <header id="masthead" class="<?php echo is_singular() && twentynineteen_can_show_post_thumbnail() ? 'site-header featured-image' : 'site-header'; ?>">
        <!-- 这里可以添加header区域的其他内容 -->
    </header>
<?php
}
?>

关键注意事项

  1. 语法一致性:同一条件块内必须全程使用同一种语法格式,不能在冒号语法和大括号语法之间切换;
  2. 标签闭合:原代码里的<header>标签末尾缺少了闭合的双引号和>,我已经在示例中修正;
  3. 分支完整性:如果else分支里的header还有其他内容,记得补充完整并确保所有HTML标签正确闭合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:29:50