Let’s say you have some WordPress code that’s looping through all your posts and outputting some of their data to the webpage. How would you get the permalink of the page outside of The Loop (as in, what’s in the browser’s address bar) rather than the post you’re currently looping through?

Typically you can use WordPress’ get_permalink() function, but if you’re inside of The Loop, that function returns the permalink of each post as it’s looping through them. To get the permalink for the page OUTSIDE of the loop you’re currently in, you can use this:

get_permalink( get_queried_object_id() );

get_queried_object_id() will get the ID of the object (post/page/whatever) of the webpage you’re on, then passing that to get_permalink will result in getting it’s permalink. Problem solved!

For one example, I was recently building a site for which I needed to loop through all Staff post type entries and include a button on each of them that if clicked, would submit a form using $_GET back to that same webpage. I used this code to get the correct permalink for the action=”” attribute of the form:

Handy dandy.

2 comments

  1. Soumya August 4, 2015 at 3:47 pm

    Reply

    Thank you!!! Victory!! I was going crazy for the last 5 hours trying to figure out how to make my form on a wordpress post return the url in the form submission email sent to me…im a newbie in coding…so it was difficult for me to figure out the error…this solved my problem thank you so much!

    • Kellen Mace August 5, 2015 at 9:04 am

      Reply

      Great! You’re very welcome. Glad this post helped you out 🙂

Leave a reply

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