Replace text string on individual page

I am looking to replace a few text strings for only two specific pages on a wordpress site. It should not affect those strings on any other pages. I'd prefer to do this via adding some code to functions.php

I think using part of this code would be the first part, just need help with the rest https://wordpress.stackexchange.com/a/278357

Topic query-string translation Wordpress

Category Web


I can't comment so I'll answer and slightly adjust Bhagyashree's which is exactly what you'll need to do based on your question. Except you may want to know how to include the 2 pages rather than duplicating the function. And also passing in an array of strings to replace.

function replace_some_text( $content ) {
   
    // Notice the || we're saying if is page1 OR page2. Also changed to is_single.
    if( is_single( 2020 ) || is_single( 2021 ) {

       $text_strings_to_replace = array( 'first_string', 'second_string', 'third_string_to_replace' );

       $content = str_replace( $text_strings_to_replace, 'new_text', $content );
       
}

       return $content;
}

add_filter('the_content', 'replace_some_text');

Little explanation. Basically, we hook into a WordPress filter hook [add_filter][1] that allows us to filter all the content on the page.

We filter the $content inside our function, in this case using a PHP function [str_replace][1] to search the content for our array of strings and replace them with 'new_text'.


I have run through the same issue from past 18 hours. I had tried multiple permutations and combinations of codes and finally, this worked for me. Put this code in the Appearance >> Theme Editor >> functions.php fie:

function replace_text( $text ) {
    if( is_page( 1709 ) ) {
       $text = str_replace('old_text', 'new_text', $text);
       $text = str_replace('old_text', 'new_text', $text);
       }

return $text;
}

add_filter('the_content', 'replace_text');
  • old_text is the text you want to replace and new_text you want to replace it with.
  • To determine the id, please edit the page, you will find the id in the URL.

Some Example Here is how to replace all instances of a string in WordPress. Just add the following code to your theme’s functions.php file:

function replace_text($text) {
    $text = str_replace('look-for-this-string', 'replace-with-this-string', $text);
    $text = str_replace('look-for-that-string', 'replace-with-that-string', $text);
    return $text;
}                                                                                           
add_filter('the_content', 'replace_text');

More info on http://php.net/manual/en/function.str-replace.php

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.