Post Pic

How to: Get permalink outside of the loop

Some days ago, rebellion, one of WpRecipes readers, asked me how to access post data outside of the WordPress loop. I have provided a solution to him, however it wasn’t possible to get a permalink outside of the loop. Here’s how to do it easily.

To get a permalink outside of the loop, you have to use the get_permalink() function. That function takes a single argument, which is the ID of the post you'd like to get the permalink:

<a href="<?php echo get_permalink(10); ?>" >Read the article</a>

You can also use this function with the $post global variable:

<a href="<?php echo get_permalink($post->ID); ?>" >Read the article</a>

Thanks to Julien Chauvin for the tip!

5 Responses

Dec 14 2008 12:09

When the global $post variable is set, you don’t have to echo get_permalink() or worry about passing in the post id argument:

<a href="">Read the article

Dec 14 2008 12:10

Whoops, the PHP got stripped out of the comment. I’ll try again:

<a href=”<?php the_permalink(); ?>”>Read the article</a>

Dec 14 2008 12:53

There’s a mistake in the link to Juliens blog. You wrote <a heref=”" instead of <a href=”"

Dec 14 2008 16:58

@Austin: Didn’t knew that works! Thanks :)
@pascal: Sorry for the typo. I have corrected it.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required