Support » Themes and Templates » How can I get the post ID from a post slug?

  • Hello,

    How can I get the post ID from a post slug in WordPress? I’m not asking for the post id of the current post in a loop. 😉

    Many thanks for your time and help.

Viewing 7 replies - 1 through 7 (of 7 total)
  • Untested by me but the author claims this does what you want.

    http://erikt.tumblr.com/post/278953342/get-a-wordpress-page-id-with-the-slug

    It says page slug … I need post slug … Do you think it’s still good ?

    Here is what I tried, in functions.php:

    <?php
    function get_ID_by_slug($page_slug) {
        $page = get_page_by_path($page_slug);
        if ($page) {
            return $page->ID;
        } else {
            return null;
        }
    }
    ?>

    and

    <?php
    function get_ID_by_slug($post_slug) {
        $post = get_post_by_path($post_slug);
        if ($post) {
            return $post->ID;
        } else {
            return null;
        }
    }
    ?>

    In my wordpress php template page where I need to get the ID of a post which has ‘josie’ as page name (slug).

    <?php $my_id = get_ID_by_slug('josie'); ?>

    Doesn’t work. :-/

    Really, if it were me:

    $id = $wpdb->get_var("SELECT ID FROM $wpdb->post WHERE post_name = 'name-of-slug');

    Is there a syntax error in your code?

    Yes. Its missing a closing double quote. Should be:

    $id = $wpdb->get_var("SELECT ID FROM $wpdb->post WHERE post_name = 'name-of-slug'");

    That is what I get for posting when I should be going to bed.

    OK it was also missing the s at posts and now it works … THANK YOU so much ! 😉

    <?php $my_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '$slug'"); ?>

    I don’t suggest using that method as multiple posts can use the same slug if they’re in different sections of your site.

    get_page_by_path is what you want to use to make sure you get the correct page because it will take into account the section of the site the slug is from.

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘How can I get the post ID from a post slug?’ is closed to new replies.