Results 1 to 5 of 5

Thread: Safe post id outside of Loop?

  1. #1
    Rarst's Avatar
    Rarst is offline Big Tipper
    Join Date
    Jul 2009
    Posts
    322

    Default Safe post id outside of Loop?

    Some widgets I want to code for new theme should be aware of post they are on.

    I can't find any way to access post id that isn't marked as inside Loop only.

    $id, $wp_query->$post, the_ID(), get_the_ID() are all supposed to work inside Loop only.

    In practice $id will have leftover value and these do work outside of Loop... But I feel like this is going against documentation.

    Any function or something I am missing?
    Rarst.net - cynical thoughts on software and web (and sometimes WP) | @Rarst | I seem to be non-GPL-compliant person. Beware my poisonous thoughts.

  2. #2
    Utkarsh is offline Hello World
    Join Date
    Nov 2009
    Posts
    73

    Default

    On single posts, you can use $wp_query->post->ID in sidebar.

  3. #3
    Rarst's Avatar
    Rarst is offline Big Tipper
    Join Date
    Jul 2009
    Posts
    322

    Default

    Quote Originally Posted by Utkarsh View Post
    On single posts, you can use $wp_query->post->ID in sidebar.
    WP_Query
    Properties
    $post
    (available during The Loop)
    As above. Technically this will work, as will rest of stuff. But by design it is in-Loop.
    Rarst.net - cynical thoughts on software and web (and sometimes WP) | @Rarst | I seem to be non-GPL-compliant person. Beware my poisonous thoughts.

  4. #4
    Utkarsh is offline Hello World
    Join Date
    Nov 2009
    Posts
    73

    Default

    Quote Originally Posted by Rarst View Post
    As above. Technically this will work, as will rest of stuff. But by design it is in-Loop.
    Not sure what would you consider as not going against the documentation, but if you use wp_reset_query(), and call the_post(), it'll restore the original query, and fetch the first post. You can then access it using $post->ID.

  5. #5
    Rarst's Avatar
    Rarst is offline Big Tipper
    Join Date
    Jul 2009
    Posts
    322

    Default

    Not sure what would you consider as not going against the documentation
    Function or variable documented as usable outside the Loop. :)

    use wp_reset_query(), and call the_post(), it'll restore the original query, and fetch the first post. You can then access it using $post->ID.
    Good idea, thanks! Will play with it.
    Rarst.net - cynical thoughts on software and web (and sometimes WP) | @Rarst | I seem to be non-GPL-compliant person. Beware my poisonous thoughts.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •