Search code examples
phpwordpresspermalinks

How to edit permalink with str_replace() Function


I'm trying to edit a wordpress permalink like the one here...

echo get_permalink();

This permalink as it is will output...

domain.com/directory/mycustompage/

I'm looking for a way using str_replace() to make the the URL to become...

domain.com/NEWDIRECTORY/?draft=mycustompage

So as you can see I want to change the middle directory to "NEWDIRECTORY" and also grab the last directory name "mycustompage" and use that as the parameter.

I apologise if this seems easy, I've just started seriously coding with PHP this year at school.

Thanks


Solution

  • This should do what you're after. I've put the URL in a variable and then exploded it and rebuilt it.

    <?php
    $url = "domain.com/directory/mycustompage/";
    $exploded = explode('/', $url);
    $newURL = $exploded[0].'/NEWDIRECTORY/?draft='.$exploded[2];
    
    echo $newURL;
    ?>
    

    Outputs domain.com/NEWDIRECTORY/?draft=mycustompage as requested