首页 > 解决方案 > 如果 (is_page_template()) 在 header.php 中不起作用

问题描述

我有 3 个单独的标题选项,都带有横幅图片: 1. 主页 2. 赞助商模板 3. 所有其他页面。

我已将以下代码放在标题中。主页和所有其他页面都按预期工作,但我似乎无法使赞助商模板工作(class="sponsor-title" 没有出现)。

<?php if ( has_post_thumbnail()) : ?>
    <?php the_post_thumbnail(); ?>
<?php endif; ?>
<?php if ( is_front_page()): ?>
    <span class="home"><h1><?php echo event_title(); ?></h1></span>
    <span class="tag-line"><?php the_field('tag_line'); ?></span>
    <span class="date"><?php the_field('date_time_header'); ?></span>
    <?php 
        $ticket = get_field('ticket_url');
        if ( $ticket ): 
            $ticket_url = $ticket['url'];
            $ticket_title = $ticket['title'];
        ?>
        <a class="button" href="<?php echo esc_url($ticket_url); ?>"><?php echo esc_html($ticket_title); ?></a>
<?php if (!is_page_template('page-templates/all-sponsor-template.php')); ?>
    <span class="sponsor-title"><h1><?php echo event_title(); ?></h1></span>
<?php endif; ?>
<?php else: ?>
    <span class="page-title"><h1><?php the_field('page_header'); ?></h1></span>
    <span class="sub-header"><?php the_field('sub_header'); ?></span>
<?php endif;?> 

我做错了什么?我想确保在选择模板或页面时出现正确的样式,因为它与其他页面非常不同。

标签: phpwordpress

解决方案


你的问题是你的if语句的语法。试试这个:

<?php if (!is_page_template('page-templates/all-sponsor-template.php')) { ?>
<span class="sponsor-title"><h1><?php echo event_title(); ?></h1></span>
<?php } else { ?>
<span class="page-title"><h1><?php the_field('page_header'); ?></h1></span>
<span class="sub-header"><?php the_field('sub_header'); ?></span>
<?php } ?>

我总是使用{..}方括号,因为它更容易理解和理解代码的逻辑。但是,要使用您尝试过的语句的正确结构重写您的代码if,它看起来像这样:

<?php if (!is_page_template('page-templates/all-sponsor-template.php')): ?>
<span class="sponsor-title"><h1><?php echo event_title(); ?></h1></span>
<?php else: ?>
<span class="page-title"><h1><?php the_field('page_header'); ?></h1></span>
<span class="sub-header"><?php the_field('sub_header'); ?></span>
<?php endif; ?>

当然,这里还有感叹号:

if (!is_page_template('page-templates/all-sponsor-template.php'))

表示“如果不是页面模板 all-sponsor-template.php”,因此如果您检查 TRUE,请将其删除。

最后,请记住,由于某些全局变量在循环期间被覆盖,is_page_template()将无法在循环中工作。但是,如果此代码在您的 中header.php,那么您应该没问题。


推荐阅读