Get Current Path in WordPress

URL Full

URL full is a complete URL consisting of protocol (http/https), host (commonly called domain), path, and query string. You can see this full URL in the address bar of your browser.

An example:
https://www.subarkah.com/test/my-current-path/?par1=abc&par2=def

Get URL Full in Vanilla PHP

function get_current_path() {
    if ( ( isset($_SERVER['HTTPS'] ) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ) ) || 
    ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' )
    ) {
        $proto = 'https://';
    } else {
        $proto = 'http://';
    }

    return $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

echo get_current_path();

Output:

https://www.subarkah.com/test/my-current-path/?par1=abc&par2=def

Get URL Full in WordPress

echo home_url( $_SERVER['REQUEST_URI'] );

Output:

https://www.subarkah.com/test/my-current-path/?par1=abc&par2=def

From the code above we can see that to get the full path by utilizing the home_url() function in WordPress the code is less than making it with vanilla PHP, you can choose the one you prefer. For performance comparison I have never tested, if you have time to test it please share the results in the comment below.

URL Relative

URL relative is a URL full without protocol and host.

An example:
/test/my-current-path/?par1=abc&par2=def

Get URL Relative in Vanilla PHP

echo $_SERVER['REQUEST_URI'];

Output:

/test/my-current-path/?par1=abc&par2=def

Get URL Relative in WordPress

$url = 'https://www.subarkah.com/test/my-current-path/?par1=abc&par2=def';
echo wp_make_link_relative( $url );

Output:

/test/my-current-path/?par1=abc&par2=def

To get the full relative path active, you basically using $_SERVER[‘REQUEST_URI’] in vanilla PHP is enough, while the wp_make_link_relative() function in WordPress is more suitable if you already have the url data, and it will be more useful if the url data is more than one (for example in an array or in a query loop). Here’s an example of its use:

$urls = [url1, url2, ...];
$rel_urls = [];
foreach( $urls as $url ){
    $rel_urls[] = wp_make_link_relative( $url );
}

URL Path

URL path is a URL relative without query string.

An example:
/test/my-current-path/

Get URL Path in Vanilla PHP

echo explode( '?', $_SERVER['REQUEST_URI'], 2 )[0];

Output:

/test/my-current-path/

Get URL Path in WordPress

global $wp;
echo $wp->request;

Output:

test/my-current-path

As you can see, getting the relative path is easier using WordPress, with the output always without slash (“/”) at the beginning and the end, it will be more consistent when we use it as a condition.

That’s it, happy coding!

Leave a Comment

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