Skip to content
Advertisement

WordPress PHP | get_permalink() stripping slashes. Cant add extra slash

I have social media buttons to share a URL. My code looks something like

$socialURL = get_permalink();

//trying to add extra slash here
$socialURL = str_replace('https://', 'https:///', $socialURL);

$facebookURL = 'https://facebook.com/sharer/sharer.php?u=' . $socialURL;

My expected URL: https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fpillartopost.online

where %2F are the 2 slashes

Result URL: https://www.facebook.com/sharer/sharer.php?u=https%3A%2Fpillartopost.online%2Fnews%2Fwater-heating-systems%2F

where there is only one %2F slash.

For some reason my str_replace method is not doing anything. I have looked through wordpress docs for other solutions and nothing was working, and this definitely seems like the most simple solution. Why would that not add an extra slash?

Advertisement

Answer

Probably, using trailingslashit with

php query builder function could solve the problem:

$social_url        = trailingslashit( get_permalink() );
$facebook_base_url = 'https://facebook.com/sharer/sharer.php';
$facebook_query    = http_build_query(
    [
        'u' => $social_url
    ]
);
$facebook_url      = "$facebook_base_url?$facebook_query";

According to trailingslashit docs:

Appends a trailing slash. Will remove trailing forward and backslashes if it exists already before adding a trailing forward slash. This prevents double slashing a string or path…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement