phpwordpressurlreturn-value

Returning current URL in WordPress


I am trying to implement canonical and hreflang tags in WordPress, but I cannot retrieve the current URL of the visited page.

I tried :

 <?php echo site_url(); ?>

But it returns https://www.example.com instead of https://www.example.com/current-page1


Solution

  • In case anyone else needs this. Below code should get the exact URL including parameters.

    home_url($_SERVER['REQUEST_URI']);
    

    You can echo or return it depending on your use case. e.g.

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

    or

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