Get the URL of the current page or post with PHP in WordPress

This ia a very quick note on the right way to get the URL of the current page or post with PHP in your WordPress template:

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

This will work for both posts and pages and outside the loop. I am using this for things like social media sharing buttons for example. Use it anywhere in your WordPress template to get the URL. Use the_permalink() only for posts and within the loop!

Hope this helps someone else wondering why the_permalink() is displaying abnormally when used outside the loop and for pages :)

If you like this page, please share it

  • http://profile.yahoo.com/Z3NKWWZUEIPFPZHPDKCISKYMDU suaskyat

    your tips is what i actually looking for! my problem till now is dynamically getting the url of a page to pass it into the href parameter of facebook comments..so still i am not getting any luck to integrate the any social media inside the subpages of my site!
     so how can i pass the url dynamically to href in this case:

     
         
        <fb:comments href="” width=”880″> 

    when i echo by using your code on one of my page i get: http://localhost/kripalphotography/home/kripal/IMG_0393.JPG
    and i want this to get passed into href using some variable by
    $ link = http://localhost/kripalphotography/home/kripal/IMG_0393.JPG

    but i get the error : “The comments plugin requires an href parameter.” please help me to solve this problem. I am using this concept with wordpress in CMS site.

    Thanks a lot!!