Get Current Page URL in WordPress

Categories:

Hello developers, sometimes we need small changes like today and wondering how to do these here is how to get current page URL to generate automatic link using PHP code. Here is I have a solution for you it doesn’t required any plugin changing too much of code I am also going to share with you getting current page URL even if you don’t use in WordPress.

Below code request WordPress to get full URL link to a page along with home link using this query you get your result don’t forget to sanitize these links and outputs.

Get Current page link URL using the_permalink

<?php esc_url(the_permalink()); ?>

Another method to get current page link in any platform based website may be it’s WordPress or not. These also works for HTTP/HTTPS links.

Also Read:

<?php 
$Path=$_SERVER['REQUEST_URI'];
echo $URI='http://www.example.com'.$Path;
?>

Adding one more code into this list

<?php echo $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>

In above example server return result are unfiltered it should be escape using WordPress appropriate code like esc_url() or esc_url_raw() :

Readย How to Secure Website? Made these changes in .htaccess

Using request query to WordPress to generate current page URL.

<?php
global $wp;
$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
?>

As $_SERVER[ 'REQUEST_URI' ] represents unfiltered user input, one should always escape the return value of add_query_arg() when the context is changed. For example, use esc_url_raw() for DB usage or esc_attr() or esc_url() for HTML.

# relative current URI:
<?php echo $current_rel_uri = add_query_arg( NULL, NULL ); ?>

#absolute current URI:
<?php echo $current_uri = home_url( add_query_arg( NULL, NULL ) ); ?>

Comments

One response to “Get Current Page URL in WordPress”

  1. gynaika Avatar
    gynaika

    Veryy gold blog! Do you have any tis annd hints for aspiring writers?
    I’m planning to start my own ebsite soon but I’m a little
    lost on everything. Would you propode starting with a
    free platform like WordPress or go for a paid option?
    There are so many choices out there that I’m completely overwhelmed ..
    Any recommendations? Thank you!

Leave a Reply

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