【问题标题】:How to add class to HTML element depending on page-template?如何根据页面模板向 HTML 元素添加类?
【发布时间】:2019-02-14 13:41:45
【问题描述】:

如果页面使用section-about.phpsection-contact.php 页面模板文件,我正在尝试将特定类layout-red 添加到我的div 元素中。如果没有,请添加类layout-default

我尝试过使用is_template(); 标签,但后来又尝试了get_page_template_slug(get_the_ID()

<?php 
    echo (get_page_template_slug);
    if ( get_page_template_slug(get_the_ID()) === 'section-about.php' ) {
        echo '<div id="wrapper" class="layout-red">';
    } else {
        echo '<div id="wrapper" class="layout-default">';
    }
?>

我预计会有一个&lt;div class="layout-red"&gt;,但最后总是得到一个&lt;div class="layout-default"&gt; 如果我在 enitre cl 之前插入 var_dump(get_page_template_slug(get_the_ID()));,它会返回 string(32) "template-parts/section-about.php"

【问题讨论】:

  • 在做 if 之前,你可以尝试 var_dump(get_page_template_slug(get_the_ID())) 看看实际返回了什么。
  • 能否提供更多关于 get_page_template_slug() 等返回的信息?
  • 返回string(32) "template-parts/section-about.php"

标签: php wordpress


【解决方案1】:

我们可以使用下面的代码来解决。

if ( basename(get_page_template_slug(get_the_ID()) === 'section-about.php' ) {
    echo '<div id="wrapper" class="layout-red">';
} else {
   echo '<div id="wrapper" class="layout-default">';
}

返回layout-red的值

【讨论】:

    【解决方案2】:

    这行得通:

    global $template; echo basename($template); //return string of current page template
    if ( basename($template) === 'section-about.php' ) {...}
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 2011-12-18
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多