首页 > 解决方案 > 将 woocommerce-loop-product__title 从 H2 更改为 H6

问题描述

我正在尝试将 Woocommerce“woocommerce-loop-product__title”从 H2 更改为 H6,但我在定位该功能时遇到了一些麻烦。

任何人都可以就插件文件中的位置提出建议,或者更好的是如何在主题functions.php文件中覆盖它?

谢谢

标签: wordpresswoocommerce

解决方案


有两种方法可以做到这一点 - 使用钩子,或者在您的 Child 主题中覆盖 WooCommerce 模板文件。首先,让我们找到代码。

您要查找的文件位于 WooCommerce 插件中:

templates/content-product.php

该文件的第 5 行说:

 This template can be overridden by copying it to yourtheme/woocommerce/content-product.php.

让我们先看一下文件覆盖。

方法 1 - 文件覆盖

templates/content-product.php从 WooCommerce 插件复制到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_template_loop_product_title从钩子中取消钩子删除函数woocommerce_shop_loop_item_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>';
}

推荐阅读