I’m not a PHP guy so no idea so how to do it, but tried something as given below.
Requirement:
<link href="<?php the_permalink(); ?>">
Currently gives me this output:
<link href="http://example.com/au/">
I need to change a part of URL at runtime using regular expression or any string replace function.
Something like this:
<link href="<?php echo str_replace("/au/","/uk/","<?php the_permalink(); ?>"); ?>"/>
I thought this would work, but instead it gives me this:
<link href="http://example.com/uk/"/>
Please advise what would be the correct solution.
First, you don’t need PHP tags when you are already in PHP tags. Second the function
the_permalink()
doesn’t actually return the value which you want, it just displays it (See this post to see more about the difference of displaying and returing: WordPress (ACF) function does not return a value)So you probably want to use
get_permalink()
here, since this function returns the value you want. Then you can also use it almost as you already tried:Instead of manually doing a string replacement each time you need this, I recommend adding the following filter to functions.php:
You can now use
the_permalink()
function as usual in your templates, and the string substitution will automatically be applied:Read more about
the_permalink
filter in the Codex.Try this: