如何根据页面模板向HTML元素添加类?

时间:2019-02-13 16:41:15

标签: php wordpress

如果该页面使用的是layout-redsection-about.php页面模板文件,我正在尝试向我的div元素添加一个特定的类section-contact.php。如果没有,请添加类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">';
    }
?>

我希望有一个<div class="layout-red">,但是经常以<div class="layout-default">结尾 如果我在enitre cl之前插入var_dump(get_page_template_slug(get_the_ID()));,它将返回string(32)“ template-parts / section-about.php”

2 个答案:

答案 0 :(得分:0)

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

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的值

答案 1 :(得分:0)

这有效:

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