WordPress.org

Forums

How can I get the post ID from a post slug? (8 posts)

  1. supergab
    Member
    Posted 3 years ago #

    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.

  2. s_ha_dum
    Member
    Posted 3 years ago #

    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

  3. supergab
    Member
    Posted 3 years ago #

    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. :-/

  4. s_ha_dum
    Member
    Posted 3 years ago #

    Really, if it were me:

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

  5. supergab
    Member
    Posted 3 years ago #

    Is there a syntax error in your code?

  6. s_ha_dum
    Member
    Posted 3 years ago #

    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.

  7. supergab
    Member
    Posted 3 years ago #

    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'"); ?>

  8. jeremy.lockhart
    Member
    Posted 3 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags