WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] $post->ID not containing current page ID (6 posts)

  1. catsoup
    Member
    Posted 2 years ago #

    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.

  2. esmi
    Forum Moderator
    Posted 2 years ago #

    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

  3. catsoup
    Member
    Posted 2 years ago #

    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.

  4. esmi
    Forum Moderator
    Posted 2 years ago #

    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

  5. catsoup
    Member
    Posted 2 years ago #

    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.

  6. esmi
    Forum Moderator
    Posted 2 years ago #

    Glad I could help :-)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags