user3102556
user3102556

Reputation: 79

WooCommerce how to change chunks of text in the final html

I need to replace a chunk of text in a WooCommerce page right before it is sent to the browser.

I have tried the following code that I found on the web :

function start_modify_html() {
   ob_start();
}

function end_modify_html() {
   $html = ob_get_clean();
   $html = str_replace( 'old string', 'new string', $html );
   echo $html;
}

add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );

It works, but unless I am missing something, it only works in the body section of the page, and the text I need to replace is located in the header section.

What am I missing?

Upvotes: 1

Views: 158

Answers (1)

mujuonly
mujuonly

Reputation: 11861

add_action('template_redirect', 'start_custom_buffer', 9999);
add_action('shutdown', 'end_custom_buffer', 1);

function start_custom_buffer() {

    ob_start();
    ob_start('end_custom_buffer');
}

function end_custom_buffer($buffer = '') {
    $buffer = str_replace( 'Shop', 'Shopreplacedd', $buffer );
    return $buffer;
}

Start buffering on teplate_redirect hook and on shutdown (the website loading end), replace the desired strings and return the buffer

Upvotes: 1

Related Questions