首页 > 解决方案 > 如何覆盖locate_template函数?

问题描述

我正在尝试将 Wordpress 的模板文件重新映射到我的主题中的子目录(类似于views文件夹)。我尝试了一些在 Wordpress 文档中找到的钩子,但没有按预期工作。

分析“包含”主题模板文件的核心功能,我在wp-includes/template.phplocate_template文件中找到了该功能。我想覆盖该功能以达到我想要的效果。

所以,原来的函数体是:

function locate_template( $template_names, $load = false, $require_once = true, $args = array() ) {
    $located = '';
    foreach ( (array) $template_names as $template_name ) {
        if ( ! $template_name ) {
            continue;
        }
        if ( file_exists( STYLESHEETPATH . '/' . $template_name ) ) {
            $located = STYLESHEETPATH . '/' . $template_name;
            break;
        } elseif ( file_exists( TEMPLATEPATH . '/' . $template_name ) ) {
            $located = TEMPLATEPATH . '/' . $template_name;
            break;
        } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {
            $located = ABSPATH . WPINC . '/theme-compat/' . $template_name;
            break;
        }
    }

    if ( $load && '' !== $located ) {
        load_template( $located, $require_once, $args );
    }

    return $located;
}

而覆盖只是将一个附加views/到 Wordpress 搜索模板文件的路径,如下所示:

function locate_template( $template_names, $load = false, $require_once = true, $args = array() ) {
    $located = '';
    foreach ( (array) $template_names as $template_name ) {
        if ( ! $template_name ) {
            continue;
        }
        if ( file_exists( STYLESHEETPATH . '/views/' . $template_name ) ) {
            $located = STYLESHEETPATH . '/views/' . $template_name;
            break;
        } elseif ( file_exists( TEMPLATEPATH . '/views/' . $template_name ) ) {
            $located = TEMPLATEPATH . '/views/' . $template_name;
            break;
        } elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {
            $located = ABSPATH . WPINC . '/theme-compat/' . $template_name;
            break;
        }
    }

    if ( $load && '' !== $located ) {
        load_template( $located, $require_once, $args );
    }

    return $located;
}

我知道修改核心函数是一个(大)错误,所以我想要的是从我的主题的functions.php文件中覆盖这个函数。我想我只需要在一些初始化钩子上重新声明这个函数,但我找不到要使用的钩子(如果这是正确的方法)。

有人可以帮我弄这个吗?

标签: phpwordpresswordpress-theming

解决方案


"I'm trying to remap Wordpress' template files to a subdirectory in my theme"

Why? Use a child theme. Anything else would be brittle and error prone.

Consider using an htaccess file for the remap.


推荐阅读