首页 > 解决方案 > 覆盖子主题中的模块

问题描述

我正在修改主题中的模块并将其添加到子主题中。该模块不是页面模板,而是一个 PHP 文件。我将文件放在子主题中与父主题相同的层次结构中,但 WordPress 没有选择子主题文件。如何让它发挥作用?

标签: phpwordpresswordpress-themingextendchild-theming

解决方案


子主题旨在覆盖模板。通常包含模板get_template_part(),基本上使用以下功能:

/**
 * Retrieve the name of the highest priority template file that exists.
 *
 * Searches in the STYLESHEETPATH before TEMPLATEPATH and wp-includes/theme-compat
 * so that themes which inherit from a parent theme can just overload one file.
 *
 * @since 2.7.0
 *
 * @param string|array $template_names Template file(s) to search for, in order.
 * @param bool         $load           If true the template file will be loaded if it is found.
 * @param bool         $require_once   Whether to require_once or require. Default true. Has no effect if $load is false.
 * @return string The template filename if one is located.
 */
function locate_template($template_names, $load = false, $require_once = true ) {
    $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 );

    return $located;
}

如您所见,STYLESHEETPATH(子主题路径)在模板路径之前被检查。但是您必须像模板一样包含文件。

无法使用子主题覆盖任意 PHP 文件。您也不会覆盖父母的functions.php,而是扩展它。

你可以做些什么来解决你的问题:

  1. 在您的子主题 functions.php 中require()包含新功能 PHP 文件include()
  2. add_filter使用或连接到您的父主题功能add_action
  3. 如果所有这些都没有帮助,请打扰父主题开发人员以增加其可扩展性

推荐阅读