1

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.

1
  • easy : <link href="<?= str_replace("au","uk", the_permalink());?>"/> Commented Mar 13, 2016 at 18:54

3 Answers 3

3

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:

<link href="<?php echo str_replace("/au/","/uk/", get_permalink()); ?>"/>
Sign up to request clarification or add additional context in comments.

Comments

2

Instead of manually doing a string replacement each time you need this, I recommend adding the following filter to functions.php:

function au_to_uk_permalink($url) {
    return str_replace('/au/','/uk/', $url);
}
add_filter('the_permalink', 'au_to_uk_permalink');

You can now use the_permalink() function as usual in your templates, and the string substitution will automatically be applied:

<?php the_permalink(); ?>
<!-- Outputs: http://example.com/uk/some-post/ -->

Read more about the_permalink filter in the Codex.

1 Comment

Thanks I'll try this.
-2

Try this:

<?php
  $link = get_permalink();
  $link = str_replace("/au","/uk",$link);
?>
<link href="<?php echo $link; ?>" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.