Home > Blockchain >  How to Use return str_replace multiple times in Wordpress php function?
How to Use return str_replace multiple times in Wordpress php function?

Time:07-25

I want to replace multiple values with placeholders, but in this way only one replace is showing up in content. Please correct me.

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