Home > Net >  How to use str_replace multiple times in Wordpress PHP function?
How to use str_replace multiple times in Wordpress PHP function?

Time:07-26

I want to replace multiple values with placeholders, but only one replace is showing up in the returned content in my code below:

function custom_the_content( $content ) {
    return str_replace('{apktitle}', get_the_title(), $content);
    return str_replace('{apkversion}', get_datos_info('version'), $content);
}
add_filter('the_content', 'custom_the_content');

CodePudding user response:

The reason it is only showing one replace is that once you return from a function, any code after it will not execute.

Luckily str_replace can take arrays as the first two arguments:

If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.

You can write it like this:

function custom_the_content( $content ) {
    $search = ['{apktitle}', '{apkversion}'];
    $replace = [get_the_title(), get_datos_info('version')];
    return str_replace($search, $replace, $content);
}
add_filter('the_content', 'custom_the_content');
  • Related