Get The Posts Page URL Dynamically in WordPress

Here’s something I discovered recently, and shows what’s cool about WordPress – it’s so big, that you could discover something that other people will find relatively straightforward.

Previously in WordPress I had been building themes with links to other pages as being static. This has worked out well for a number of years. However recently a mistake occurred when we put the site live with a link back to the staging site.

That isn’t good, so I began to look for alternatives. I had heard of get_permalink(), which gets the permalink of any page or post ID, so I began to think of how the option is saved in the database, and what that option is called.

After a big of digging, I found that 'page_for_posts' is the name of the option, and it’s stored as an ID. Brilliant! This makes life easier, so after a bit of reading, I found that this option is only present when a separate option – 'show_on_front' – is set to “page”, so we need to run a check to make sure that the home page of the blog is a proper page. If not, we simply return the home page using home_url().

Code To Get the Posts Page URL

/**
 * Get the posts page URL in WordPress
 *
 * @link   https://www.winwar.co.uk/2015/10/get-the-posts-page-url-dynamically-in-wordpress/?utm_source=codesnippet
 * 
 * @return string
 */
function winwar_get_post_page_url() {

	if( 'page' == get_option( 'show_on_front' ) ) {
		
		return get_permalink( get_option('page_for_posts' ) );

	} else {

		return home_url();

	} 

}

Simple eh?

This may be simple to some, but it was something I was unaware of until recently. So if you feel intimidated in the WordPress Community, don’t be, as you probably know more than you think!

Similar Posts