WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Post ID from Slug (7 posts)

  1. KatyaKarski
    Member
    Posted 4 years ago #

    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!

  2. Galaxy_High
    Member
    Posted 4 years ago #

    Like this?

    <?php
    if ( is_page('slug') ); { include 'the_ID()'; }
    elseif { ( is_page('slug_alternative') ); { include 'the_ID()'; }
    else { echo 'Error message'; } ?>
  3. KatyaKarski
    Member
    Posted 4 years ago #

    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.

  4. MichaelH
    Member
    Posted 4 years ago #

    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;
    }
    ?>
  5. KatyaKarski
    Member
    Posted 4 years ago #

    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!

  6. MichaelH
    Member
    Posted 4 years ago #

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

  7. KatyaKarski
    Member
    Posted 4 years ago #

    Brilliant, cheers! :)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.