【发布时间】:2020-11-26 01:56:49
【问题描述】:
我正在尝试将 Woocommerce“woocommerce-loop-product__title”从 H2 更改为 H6,但我在定位该功能时遇到了一些问题。
谁能建议插件文件中的位置,或者更好的是如何在主题functions.php文件中覆盖它?
谢谢
【问题讨论】:
标签: wordpress woocommerce
我正在尝试将 Woocommerce“woocommerce-loop-product__title”从 H2 更改为 H6,但我在定位该功能时遇到了一些问题。
谁能建议插件文件中的位置,或者更好的是如何在主题functions.php文件中覆盖它?
谢谢
【问题讨论】:
标签: wordpress woocommerce
有两种方法可以做到这一点 - 使用钩子,或者通过覆盖您的 Child 主题中的 WooCommerce 模板文件。首先,让我们找到代码。
您要查找的文件在 WooCommerce 插件中:
templates/content-product.php
这个文件的第 5 行说:
This template can be overridden by copying it to yourtheme/woocommerce/content-product.php.
让我们先看看文件覆盖。
方法 1 - 文件覆盖
将 WooCommerce 插件中的 templates/content-product.php 复制到您的 Child 主题中的 woocommerce/content-product.php。该文件现在覆盖插件中的模板。我们对这个新文件进行所需的编辑。
默认content-product.php模板文件中的标题输出如下:
echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h2>';
在 WooCommerce 文件 includes/wc-template-functions.php 中定义。
如果您搜索 woocommerce_template_loop_product_title(),您将看到定义的函数:
if ( ! function_exists( 'woocommerce_template_loop_product_title' ) ) {
/**
* Show the product title in the product loop. By default this is an H2.
*/
function woocommerce_template_loop_product_title() {
echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h2>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
}
content-product.php文件中的这行代码:
do_action( 'woocommerce_shop_loop_item_title' );
调用函数woocommerce_template_loop_product_title,这是我们要覆盖的函数。因此,让我们注释掉该行,并将其替换为您的代码:
// do_action( 'woocommerce_shop_loop_item_title' );
echo '<h6 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h6>';
简单!
方法 2 - 使用 Hooks
另一个选项是从 woocommerce_shop_loop_item_title 钩子中取消删除 woocommerce_template_loop_product_title 函数并用我们自己的函数替换它。您可以通过将以下代码添加到您的 functions.php 文件来做到这一点:
remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
add_action('woocommerce_shop_loop_item_title', 'soChangeProductsTitle', 10 );
function soChangeProductsTitle() {
echo '<h6 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h6>';
}
【讨论】: