Function Friday #22: get dynamic information about your Posts page

Function Friday #22

Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.

When highlighting handy WordPress functions, it would be remiss of me to leave out this humble (but highly useful) function. If you’ve got a static page as your front page and another page containing all of your posts in your Reading settings, it’s likely that you’ll want to link to that Posts page somewhere on your site, use its page title, or even display its featured image.

Rather than hard-coding this into your theme, there’s a function that will grab the page’s ID so you can display that information dynamically.

The code

    <a href="<?php the_permalink( get_option( 'page_for_posts' ) ); ?>">
        <?php echo get_the_title( get_option( 'page_for_posts' ) ); ?>

The get_option function with the page_for_posts parameter returns the ID of the page you’ve selected as your Posts page, which you can then pass on to all kinds of functions. Here I’ve used it to get the permalink and the title of the Posts page.

The above code will output something like this:

<p><a href="">Latest posts</a></p>

This is much more robust than writing “Latest posts” or “/blog” right into your theme code.

You can use this in any function that lets you pass in a page ID, such as get_the_post_thumbnail to display the Posts page’s featured image.

Where does it go?

This code would go in any theme or plugin file where you want to retrieve information about the Posts page. More thoughts on code location are in the first Function Friday post.


Leave a Reply

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