更改“woocommerce_template_loop_product_title”标题标签

Jac*_*aly 4 php wordpress woocommerce hook-woocommerce

我正在尝试将 WooCommercewoocommerce-loop-product__title从 a更改H2为 a h6,但遇到了一些麻烦。

我使用以下代码片段来取消原始函数并将其替换为h6. 不幸的是,这确实添加了h6但它也保留了原来的h2.

有人能指出哪里出了问题吗?

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>';
}
Run Code Online (Sandbox Code Playgroud)

7uc*_*f3r 5

首先,我们要将 a 应用于remove_action现有标题。10为此使用优先级(这是 WooCommerce 中的默认设置,请参阅随附的代码行)。

从/includes/wc-template-hooks.php第 98 行复制/粘贴@version 2.1.0

add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用的主题与 WooCommerce 中的默认行为不同,优先级编号可能会有所不同(简而言之,这取决于主题)

然后,我们将根据现有输出,用我们想要的输出覆盖现有输出(我们刚刚删除的输出)。现有的输出可以在我之前在答案中引用的同一文件中找到,即第 1165 行 @version 2.1.0

所以你得到:

/**
 * Show the product title in the product loop. By default this is an H2.
 */
function action_woocommerce_shop_loop_item_title() {
    // Removes a function from a specified action hook.
    remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
    
    echo '<h6 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h6>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );
Run Code Online (Sandbox Code Playgroud)

或者仅将此应用于相关产品(单个产品页面),请使用:

function action_woocommerce_shop_loop_item_title() {
    global $woocommerce_loop;

    // Only for related products
    if ( isset( $woocommerce_loop['name']) && $woocommerce_loop['name'] === 'related' ) {
        // Removes a function from a specified action hook.
        remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
        
        echo '<h6 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes', 'woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h6>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );
Run Code Online (Sandbox Code Playgroud)