Home / Admin / Search and replace text strings
Duplicate Snippet

Embed Snippet on Your Site

Search and replace text strings

This snippet searches for 'old' text and replaces it with the new text. This way you can add text strings in your text that can change.

For example, I want all the instances of the amount of days 'guarantee' to be changable with 1 edit.

In all texts I have the text wp_code_guarantee_days, which this code will change to 60.

Code Preview
php
<?php
function replace_multiple_texts_on_the_fly($content) {
    // Array of text pairs to find and replace
    $text_pairs = array(
        'wp_code_guarantee_days' => '60',
        'wp_code_dagen_garantie' => '60',
        // Add more pairs as needed
    );
    
    foreach ($text_pairs as $old_text => $new_text) {
        // Use str_replace for simple text replacement
        $content = str_replace($old_text, $new_text, $content);
        
        // Alternatively, use preg_replace for more complex patterns
        // $content = preg_replace('/\b' . preg_quote($old_text, '/') . '\b/', $new_text, $content);
    }
    
    return $content;
}
// Apply the replacement to post content
add_filter('the_content', 'replace_multiple_texts_on_the_fly');
// Apply the replacement to post titles
add_filter('the_title', 'replace_multiple_texts_on_the_fly');
// Apply the replacement to post excerpts
add_filter('get_the_excerpt', 'replace_multiple_texts_on_the_fly');
// Apply the replacement to widget text
add_filter('widget_text', 'replace_multiple_texts_on_the_fly');

Comments

Add a Comment