Woocommerce 有条件地加载自定义产品模板

Woocommerce conditionally load a custom product template

我正在创建自定义主题,我已将文件 content-product.php 复制到我的主题文件夹中。在那里,我对 html 结构和 css 进行了更改。我可以加载产品列表并通过短代码 [products].

查看更改

但是我想在网站的其他地方显示另一个产品列表,但属于不同的类别。我会使用短代码 [products category="special category"] 这些产品应使用不同的模板显示。

我的问题是:在哪里可以检查简码查询?以及如何根据显示的产品有条件地加载不同的模板?

在我的主题 functions.php 文件中,我已经开始像这样扩展 [products] 简码:

function my_wc_shortcode_product_query_args($args, $atts){

    if ( isset( $args['category'] ) && $args['category'] == "Daoine Óga") {
        var_dump($args);
    // Tell Woocommerce to load my custom template instead of the my-theme/woocommerce/content-product.php
    }
    return $args;

}

但我不确定此时如何 return 或让 woocommerce 显示我的自定义模板。

可以在 plugins/woocommerce/includes/shortcodes/class-wc-shortcode-products.php

找到创建 [products] 简码的 woocommerce 文件

plugins 文件夹中创建一个名为 custom-product-templates 的文件夹,并将 woocommerce 文件 class-wc-shortcode-products.php 复制到该文件夹​​。

将插件注释添加到该文件的顶部:

/*
Plugin name: Custom Product Template
Plugin URI: https://anirishwebdesigner.com
Description: Display custom product templates in woocommerce loop 
Author: Linda Keating
Author URI: http://anirishwebdesigner.com
Version: 1.0
*/

在浏览器中导航到 localhost/wp-admin 和插件并激活新创建的插件

我现在可以安全地编辑该文件,以便简码行为根据特定条件加载我想要的模板。

首先扩展 class 使其接受 template 属性

在解析属性函数中添加

'template' => '',

然后搜索wc_get_template_part('content', 'product');并修改这里的代码,在if..else语句中加载不同的模板。类似于:

`if($this->attributes['template'] == 'Daoine Óga') {
    wc_get_template_part( 'content', 'childrenproduct' );
     } else {
    wc_get_template_part( 'content', 'product' );
 }`

如果有更简单/更好的解决方案,请告诉我。