[SOLVED] How to replace 3 strings in post title?


I have this code:

<?php $wptitle = get_the_title( get_the_ID() ); $wptitle = str_replace(" – word1 word2", "", $wptitle); echo $wptitle; ?>

But it does now work. When I put only one sting it works perfectly. I’m working in WordPress


Opening php tag declares that the following code should be interpreted as PHP by the server (rather than just HTML and being passed onto the client)


The following line declares a variable with the identifier (name) $wptitle and sets its value equal to the result of calling the function get_the_title with the argument get_the_ID. these functions must be declared elsewhere.

$wptitle = get_the_title( get_the_ID() );

The next one reassigns the variable $wptitle to be the same string with the string "foo" being replaced by the string "bar"

 $wptitle = str_replace("foo", "bar", $wptitle);

If you want to replace some more strings then you can repeat this line

$wptitle = str_replace("baz", "blink", $wptitle);

In such case all occurrences of the string "foo" and "bar" will be replaced.

Alternatively you can pass arrays to str_replace to perform multiple replacements in one go.

$wptitle = str_replace(array("foo", "bar", "baz"), "", $wptitle);

The next line prints out the contents of the variable $wptitle

 echo $wptitle; 

Finally this line instructs the PHP interpreter that the PHP block is over


For more information on the semantics of str_replace have a look at the php manual page

Answered By – faire

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *