• Resolved Gustav

    (@4ever16)


    I want to change multiple words in wordpress titles. But i can only change 1 word.
    How can i re-do this php script so it can change multiple words?

    For example word WORDPRESS & WORDPRESS2

    Working but only changes 1 word.

    function wpse_filter_post_titles( $title ) {
    return str_replace( 'WORDPRESS', 'REPLACETOTHIS', $title );
    }
    add_filter( 'the_title', 'wpse_filter_post_titles' );

    I tried this 2 codes but it breaks whole site.

    function wpse_filter_post_titles( $title ) {
    return str_replace( 'WORDPRESS', 'REPLACETOTHIS', $title );
    return str_replace( 'WORDPRESS2', 'REPLACETOTHIS2', $title );
    }
    add_filter( 'the_title', 'wpse_filter_post_titles' );
    function wpse_filter_post_titles( $title ) {
    return str_replace( 'WORDPRESS', 'REPLACETOTHIS', $title ) && return str_replace( 'WORDPRESS2', 'REPLACETOTHIS2', $title );
    }
    add_filter( 'the_title', 'wpse_filter_post_titles' );
    • This topic was modified 7 years, 9 months ago by Gustav.
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Jan Dembowski

    (@jdembowski)

    Forum Moderator and Brute Squad

    I can’t recall why but you may get better results adding preg_match_all.

    http://php.net/manual/en/function.preg-match-all.php

    Put it in array and in a loop replace all found instances in the array with what you want in that filter.

    You can use arrays for both the pattern and the replacement parameters for str_replace.
    Just make sure that they don’t match each other (like WORDPRESS and WORDPRESS2), so you get the result you want.

    Dion

    (@diondesigns)

    Here’s your first function, written in a slightly different way:

    function wpse_filter_post_titles($title) {
    	$title = str_replace('WORDPRESS', 'REPLACETOTHIS', $title);
    	return $title;
    }
    add_filter('the_title', 'wpse_filter_post_titles');

    If you want multiple replacements, you can copy the line with str_replace() and it will not cause a PHP fatal/parse error.

    I suspect that either preg_replace(), or str_replace() with arrays, would be a better solution than the above. But that would depend on the actual strings you want to replace. Since you didn’t provide actual strings, and it appears you are at a beginner level with PHP, I thought the “baby steps” approach would be more appropriate.

    Thread Starter Gustav

    (@4ever16)

    Thanks its solved now!

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Change multiple words in title with a function’ is closed to new replies.