WooCommerce从我的插件文件夹加载并自定义archive-product.php

Vig*_*ani 2 php wordpress woocommerce

我试图从my-plugin文件夹加载模板文件,而不是使用默认的woocommerce模板.我想从my-plugin文件夹模板结构自定义商店页面库,所以我编辑archive-product.php注释并检查哪个显示空白页面,但它加载默认的woocommerce模板(archive-product.php).我已经将模板文件移动到文件my-plugin/woocommerce/夹这是我试过的代码

 function cc_woocommerce_locate_template($template, $template_name, $template_path) {

        global $woocommerce;
        global $post;
        $plugin_path = untrailingslashit(plugin_dir_path(__FILE__)) . '/woocommerce/';
    //returns my-plugin folder with base file name echo $plugin_path;
               //   echo $template_name;
            if (file_exists($plugin_path . $template_name)) {
                $template = $plugin_path . $template_name;
               // var_dump($template);
                return $template;
            }

        return $template;
    }
Run Code Online (Sandbox Code Playgroud)

而我指出的钩子是

add_filter('woocommerce_locate_template', 'cc_woocommerce_locate_template', 1, 3);
Run Code Online (Sandbox Code Playgroud)

Dan*_*jel 7

我测试了提供的代码,它运行没有问题,因此在这种情况下最好重新开始.创建一个新插件并粘贴下面的代码.它包含两个过滤器:

wc_get_template_part - 用于循环中使用的模板

woocommerce_locate_template - 适用于所有其他模板


//
// get path for templates used in loop ( like content-product.php )
add_filter( 'wc_get_template_part', function( $template, $slug, $name ) 
{ 

    // Look in plugin/woocommerce/slug-name.php or plugin/woocommerce/slug.php
    if ( $name ) {
        $path = plugin_dir_path( __FILE__ ) . WC()->template_path() . "{$slug}-{$name}.php";    
    } else {
        $path = plugin_dir_path( __FILE__ ) . WC()->template_path() . "{$slug}.php";    
    }

    return file_exists( $path ) ? $path : $template;

}, 10, 3 );


// get path for all other templates.
add_filter( 'woocommerce_locate_template', function( $template, $template_name, $template_path ) 
{ 

    $path = plugin_dir_path( __FILE__ ) . $template_path . $template_name;  
    return file_exists( $path ) ? $path : $template;

}, 10, 3 );
Run Code Online (Sandbox Code Playgroud)

现在woocommerce在插件主文件夹中创建一个子文件夹并复制原始文件archive-product.phpcontent-product.php.最后,在该文件中进行一些小修改(回显),看看它们是否已加载.我测试了这个示例,模板在以下层次结构中加载没有问题:

主题/ template_path/TEMPLATE_NAME

主题/ TEMPLATE_NAME

插件/ template_path/TEMPLATE_NAME

默认/ TEMPLATE_NAME