How to filter WooCommerce page title?

517 Views Asked by At

I want to filter the shop page title by adding <span>-tags within the <h1>. In the archive-product.php-file, the following code is present:

<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
        <h1 class="woocommerce-products-header__title page-title"><?php woocommerce_page_title(); ?></h1>
    <?php endif; ?>

I don't really understand how I can use this filter. I could add <span> with a custom templatembut I want to know if this filter could be used instead. Or is it only for actually displaying the title?

When looking into the actual function woocommerce_page_title it does seem like it can be filtered:

$page_title = apply_filters( 'woocommerce_page_title', $page_title );

But when I add a filter to woocommerce_page_title, nothing happens. I have tried adding it with add_action('plugins_loaded') and add_action('init') but it doesn't work, for example:

function lcp_wc_filters() {

    add_filter('woocommerce_page_title',function($page_title) {
        return '<span>' . $page_title . '</span>';
    });
}

add_action('plugins_loaded','lcp_wc_filters');
2

There are 2 best solutions below

0
Erika On BEST ANSWER

The following worked with the 'init'-hook:

function filter_woocommerce_page_title( $page_title ) {
    return '<span>'. $page_title . '</span>';
};

function lcp_wc_hooks() { 
    add_filter( 'woocommerce_page_title', 'filter_woocommerce_show_page_title', 10, 2 );
}

add_action('init','lcp_wc_hooks');
2
Daniyal Sedighpour On

use this code

function filter_woocommerce_show_page_title( $array, $int ) { 
    return '<h1 class="woocommerce-products-header__title page-title"><span>'.implode(' ', $array).'</span></h1>';
}; 
add_filter( 'woocommerce_show_page_title', 'filter_woocommerce_show_page_title', 10, 2 );