为WooCommerce类别存档页面添加产品标题标题标签

问题描述

我希望更改产品类别页面显示的产品的标题标签(从无标题标签更改为H2),但仅在产品类别页面

我找到了2个有效的解决方案,但是它们也更改了我不想在其他页面显示的产品的标题标签

1。通过更改content-product.PHP文件中的标题标签

它可以工作,但是也会更改产品页面上相关产品中显示的产品。

<div class="Box-text <?PHP echo flatsome_product_Box_text_class(); ?>">
    <?PHP
        do_action( 'woocommerce_before_shop_loop_item_title' );

        echo '<h2 class="title-wrapper" style="font-size: 100%">';
        do_action( 'woocommerce_shop_loop_item_title' );
        echo '</h2>';

2。通过在woocommerce-loop-product中的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 '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes','woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h2>';
}

也许第一个解决方案是最好的,然后我只需要在related.PHP文件或funtions.PHP文件添加代码,因为标题标签的更改不适用于相关产品?

我从未学习过编码,在这里被封锁了。

解决方法

您可以按如下方式使用条件标签is_product_category()

1。通过更改content-product.php文件中的标题标签

<div class="box-text <?php echo flatsome_product_box_text_class(); ?>">
<?php
    do_action( 'woocommerce_before_shop_loop_item_title' );
    
    if( is_product_category() ) { 
        echo '<h2 class="title-wrapper" style="font-size: 100%">';
    }

    do_action( 'woocommerce_shop_loop_item_title' );

    if( is_product_category() ) {
         echo '</h2>';
    }

2。或通过在functions.php文件中插入代码woocommerce_shop_loop_item_title挂钩

add_action('woocommerce_shop_loop_item_title','product_heading_title_on_category_archives',1 );
function product_heading_title_on_category_archives() {
    if( is_product_category() ) { 
        remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title',10 );
        add_action('woocommerce_shop_loop_item_title','change_product_heading_title',10 );
    }
}
function change_product_heading_title() {
    echo '<h2 class="' . esc_attr( apply_filters( 'woocommerce_product_loop_title_classes','woocommerce-loop-product__title' ) ) . '">' . get_the_title() . '</h2>';
}