49

I'm trying to use the front page as a default of sorts for featured images (if no featured image is set, I want to use the front page's, for example)

But I'm having trouble finding out how to get the post ID of the front page in a safe manner (so that my code still works when the front page is inevitably changed by someone)

I know I could just hard code an ID in my code, but that'll break when someone decides to use a new content item as the front page.

Would I have to use wp-query to achieve this? And if so, what is a safe way to achieve this with wp-query?

2 Answers 2

104

WordPress has a few useful options. You can get the homepage ID by using the following:

$frontpage_id = get_option( 'page_on_front' );

or the blog ID by using:

$blog_id = get_option( 'page_for_posts' );

Here's a list of many useful get_option parameters.

1
  • 8
    get_option(...) will return the id as STRING, if you want it to be an INTEGER => do (fastest) direct type cast (int) => eg.: $frontpage_id = (int)get_option( 'page_on_front' );
    – jave.web
    Sep 2, 2016 at 13:48
12

You should be able to use $front_page_id = get_option( 'page_on_front' );

It'll return the ID of the page you're using as your site's front page, or 0 if it hasn't been set.

Codex: get_option()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.