Cray
Cray

Reputation: 5483

WooCommerce: Change related products heading and remove/change <h2>

I want to change the title text of the related products and remove the <h2> for SEO reasons.

I found some answers to change the title text here: Rename Related Products title in Woocommerce 3 But the code from there and the answer doens't work (anymore?).

And there is an other problem. The heading uses the <h2> tag which I want to change also.

I found the following code in the related.php template:

<?php
$heading = apply_filters( 'woocommerce_product_related_products_heading', __( 'Related products', 'woocommerce' ) );

if ( $heading ) : ?>
    <h2><?php echo esc_html( $heading ); ?></h2>
<?php endif; ?>

Is there any way to chage the complete output of $heading without changing the template file?

Upvotes: 3

Views: 4784

Answers (1)

Howard E
Howard E

Reputation: 5639

First you can remove the existing h2 by adding a filter

add_filter('woocommerce_product_related_products_heading', function(){return false;});

Then you can re-write the woocommerce_product_loop_start function which is pluggable.

function woocommerce_product_loop_start( $echo = true ) {
    ob_start();

    wc_set_loop_prop( 'loop', 0 );

    wc_get_template( 'loop/loop-start.php' );

    $loop_start = apply_filters( 'woocommerce_product_loop_start', ob_get_clean() );

    if ( $echo ) {
        // check to see if it's the related loop
        if (wc_get_loop_prop('name') == 'related'){
            // Change the heading to whatever you want
            echo "<h3>Related Products</h3>";
        }
        echo $loop_start; // WPCS: XSS ok.
    } else {
        return $loop_start;
    }
}

Upvotes: 5

Related Questions