WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Post ID from Slug

[Resolved] Post ID from Slug

  • Hi guys! Hope you can help.

    I’m doing some funky template stuff and I need to pull the ID of a post based on the slug. I’m doing this in a category template – is there a way I can pull the Post ID if I know its slug?


    the simplified version of the background story is, I have a post corresponding to each category and I want to be able to display the post at the top of the category template – but it needs to be nice and dynamic so I can’t go hard-coding IDs around the place – the category slug will match the post slug, so I need to pull the post ID based on the slug, so I can use get_post to display it.

    Cheers for your help fellas!

Viewing 6 replies - 1 through 6 (of 6 total)
  • Like this?

    <?php
    if ( is_page('slug') ); { include 'the_ID()'; }
    elseif { ( is_page('slug_alternative') ); { include 'the_ID()'; }
    else { echo 'Error message'; } ?>

    thanks, but that’s not really similar in any way – I need to pull the ID of a post (not a page) and not on that post, but on a category template, based solely on knowing the post-slug.

    There is the way

    <?php
    $slug_to_get = 'new-post';
    $args=array(
      'name' => $slug_to_get,
      'post_type' => 'post',
      'post_status' => 'publish',
      'showposts' => 1,
      'caller_get_posts'=> 1
    );
    $my_posts = get_posts($args);
    if( $my_posts ) {
    echo 'ID on the first post found '.$my_posts[0]->ID;
    }
    ?>

    Thank you Michael, I had no idea get_posts could retrieve based on the slug, that part isn’t documented in the codex, thanks so much for your help!

    Remember almost everything here can be used with get_posts – query_posts()

    Brilliant, cheers! 🙂

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘[Resolved] Post ID from Slug’ is closed to new replies.