Why does `url_to_postid` return 0 when testing `page_for_posts` Page?

If I set Reading Settings > Posts Page (in other words, the page_for_posts option) to a static page, and then attempt to pass its URL through url_to_postid() it will return 0 – why is it?

I understand that it’s technically no longer a static/post page, but is the posts page, however that page still has an ID and I still need to get at it. Funny enough, I need to get the ID in order to test if it is the same value as page_for_posts. I can’t use the 0 returned from the url_to_postid function because 0 can be returned for a number of reasons.

Does anyone know how I can test the current URL to get its ID, when it’s set to the page_for_posts page?

3 Answers
3

The reason you get 0 back is because of the test at the end of the function:

if ( ! empty( $query->posts ) && $query->is_singular )
    return $query->post->ID;
else
    return 0;

The posts page doesn’t pass the is_singular test so 0 is returned.

If you have a URL and want to know if it’s the posts page, you can match it against the permalink returned from get_permalink when passed the page_for_posts option:

$page_for_posts_url = get_permalink( get_option( 'page_for_posts' ) );
if( $current_url == $page_for_posts_url ) echo 'this is the page for posts!';

Leave a Comment