更改特定产品类别页面的 Wordpress 模板

Changing Wordpress template for specific product category page

我正在尝试更改特定产品类别页面的模板,但我无法让它正常工作。我试过 taxonomy-product_cat-the-category 但无济于事。如果有区别的话,我将 wpml 与 3 种不同语言的类别一起使用。我已经尝试使用 3 种语言中的每一种的 slug,但仍然无法正常工作。不明白是什么原因造成的。

您无法更改特定类别的 WP 模板,但是

  • 仅用于覆盖设计:您可以通过在每个 class,ID 或标签名称如下:

    body.term-车h1 { 红色; 字体大小:22px; }

  • 为了增强布局:或添加一些新功能,您可以使用 wooommerce 默认功能,例如:$term->name; in archive-product.php 在您的子主题中。

示例:

if($term->name == "car") {
   // your code will goes here
}

首先从 WooCommerce 插件目录复制 taxonomy-product_cat.php & archive-product.php - wordpress\wp-content\plugins\woocommerce\templates 到你的主题 - wordpress\wp-content\themes\your-theme\woocommerce.

然后在主题的 woocommerce 目录中复制 archive-product.php 个文件,例如 archive-product-2.phparchive-product-3.php 等。稍后您将根据您的类别修改这些文件。

然后打开taxonomy-product_cat.php文件。代码如下所示。

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

wc_get_template( 'archive-product.php' );

我们需要根据我们的条件修改这段代码中的模板调用wc_get_template()

首先获取当前类别slug,然后我们可以比较slug。根据 slug,我们将调用不同的存档产品文件。

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

// Get current category slug
global $wp_query;
$cat_slug = $wp_query->query_vars['product_cat'];

// Call template conditionally
if($cat_slug == 'accessories') {
    wc_get_template( 'archive-product-2.php' );
} else  {
    wc_get_template( 'archive-product.php' );   
}

更新

根据我的经验,最好的方法是通过复制到主题文件来避免 WooCommerce 模板被覆盖。 WooCommerce 定期更新模板,最好每次都更新模板以避免将来出现问题。因此,如果可能,除了模板覆盖之外,尽量使用过滤器挂钩。