首页 > 解决方案 > 如何覆盖 woocommerce 产品图像模板

问题描述

我想为产品图像和画廊缩略图使用我自己的自定义模板文件(具有自定义名称),因此需要使用以下方法覆盖默认的 Woocommerce 产品图像模板:

add_filter( 'wc_get_template', 'modify_product_gallery_template', 10, 5 );
function modify_product_gallery_template( $located, $template_name, $args, $template_path, $default_path ) {
    if ( 'single-product/product-image.php' == $template_name ) {
        $located = '... my-gallery.include.php';
    }

    return $located;
}

但还没有成功。有没有其他方法可以做到这一点?

标签: phpwordpresstemplateswoocommercepath

解决方案


这是一个路径问题,例如必须是绝对服务器路径get_theme_file_path()

假设您的自定义模板文件已命名my-gallery.include.php并且如果:

1)它位于您将使用的活动主题的根目录中:

$located = get_theme_file_path('/my-gallery.include.php');

所以在你的代码中:

add_filter( 'wc_get_template', 'modify_product_gallery_template', 10, 5 );
function modify_product_gallery_template( $located, $template_name, $args, $template_path, $default_path ) {
    if ( 'single-product/product-image.php' == $template_name ) {
        $located = get_theme_file_path('/my-gallery.include.php');
    }
    return $located;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

2)它位于woocommerce子文件夹上的活动主题内,您将使用:

$located = get_theme_file_path('/woocommerce/my-gallery.include.php');

3)如果您想通过您的活动主题覆盖模板,只需将文件从 woocommerce 插件复制到:woocommerce/single-product/product-image.php...</p>

现在您可以打开编辑复制的模板并在没有实际代码的情况下进行更改,并且更改将在保存后出现。


推荐阅读