Support » Plugins and Hacks » Hacks » $post->ID not containing current page ID

  • Resolved catsoup

    (@catsoup)


    Hi,

    I have been writing a plugin and need to get the current page ID.

    The various docs and pages say that it can be found in $post->ID, however I have found that its not there if the user is viewing the posts page. (i.e. the page set in Settings>Reading>Posts page) If the user is on that page then $post->ID contains the first post to be displayed.

    Anyone know how to find the page id?

    If there was a function is_current_page_the_posts_page() then:

    if (is_current_page_the_posts_page()) {
    $id=get_option(“page_for_posts”);
    } else {
    $id=$post->ID;
    }

    Would do, but so far I have not found a function to test if the current page is the posts page.

    Any ideas?

    Cheers,

    Chris.

Viewing 5 replies - 1 through 5 (of 5 total)
  • esmi

    (@esmi)

    Forum Moderator

    The is_home() conditional checks for the main posts page. You can also grab the ID of the main posts’ page using <?php $id = get_option('page_for_posts ');?>.
    http://codex.wordpress.org/Function_Reference/get_option

    I thought is_home() checked for the home page, not necessarily the posts page?

    Maybe I was not clear, but my question was meant to say that I need the ID of any page the user is visiting. $post->ID is not reliable because it does not work on the posts page (which the user can set to whatever they like).

    Thanks,

    Chris.

    esmi

    (@esmi)

    Forum Moderator

    is_home()
    When the main blog page is being displayed. This is the page which shows the time based blog content of your site, so if you’ve set a static Page for the Front Page (see below), then this will only be true on the Page which you set as the “Posts page” in Administration > Settings > Reading.

    http://codex.wordpress.org/Conditional_Tags#The_Main_Page

    Thanks!

    For anyone else looking for a solution to this, my snippet of code with Esmi’s conditional reliably gets the page id, even if its the posts page:

    if (is_home()) {
    $id=get_option(“page_for_posts”);
    } else {
    $id=$post->ID;
    }

    Thanks again Esmi!

    Regards,

    Chris.

    esmi

    (@esmi)

    Forum Moderator

    Glad I could help 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘$post->ID not containing current page ID’ is closed to new replies.