【问题标题】:How to detect the current template being displayed in WordPress?如何检测 WordPress 中显示的当前模板?
【发布时间】:2012-12-06 05:33:13
【问题描述】:

我正在开发一个 21 岁主题的儿童主题。我需要在博客页面中进行一些自定义。我想在id = "primary" 的位置添加一个类。如何发现哪个模板正在渲染页面?

【问题讨论】:

  • 嗨,试试 index.php 文件。当没有 home.php 文件存在时,它会将主页放在一起。
  • This article 很好地解释了什么主题文件用于什么目的。

标签: wordpress wordpress-theming


【解决方案1】:

在您的子主题的functions.php 中使用以下代码。
如果没有,请创建一个空的并仅使用 php opening tag (<?php)。

这将在the_content 中打印当前正在显示的主题和模板。

看到主页面:子主题index.php

看到一个帖子:子主题没有single.php

使用过滤器向内容添加调试:检查 cmets
add_filter( 'the_content', 'so_13737534_print_template', 20 );

function so_13737534_print_template( $content ) 
{
    // $template value equals to:
    // /public_html/wp-content/themes/theme-name/template-name.php
    global $template;

    // Return normal content if seeing the backend 
    // or the user is not administrator
    if( is_admin() || !current_user_can( 'delete_plugins' ) )
        return $content;

    // Split the value and build the output html
    $split_path = explode( '/', $template );
    $total = count( $split_path ) - 1;
    $theme_and_template = $split_path[$total-1] . '/' . $split_path[$total];
    $print = '<strong style="font-size:1em;background-color:#FFFDBC;padding:8px">Current = ' . $theme_and_template . '</strong>';

    // Add our output before the_content
    $content = $print . $content;
    return $content;
}

同样可以打印为&lt;head&gt;中的Html注释,使用:

add_action( 'wp_head', 'so_13737534_print_template_in_head', 999 );

function so_13737534_print_template_in_head() 
{
    global $template;
    echo '
    <!--

    TEMPLATE = ' . $template . '

    -->
    ';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 2011-09-09
    • 2012-03-16
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多