Jul 17, 2015
Get Permalink of Page Outside of The Loop
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!
Example
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 a $_GET
request back to that same webpage. I used this code to get the correct permalink for the action=""
attribute of the form:
<form id="staff-bio-button" class="staff-bio-button" action="<?php echo esc_attr( get_permalink( get_queried_object_id() ) ); ?>" method="get">
<input type="hidden" name="staff-id" value="<?php echo esc_attr( $post->ID ); ?>" />
<input type="submit" name="submit" value="Bio" />
</form>
Handy dandy.