WordPress – Get ID by post or page name

2008-03-17 @ 21:42

If you use WordPress as CMS tool or are into making plugins you might have used the wp_list_pages function? I think it’s a good function but what I don’t like is that you can exclude or include pages with the ID and not by NAME. I however found a solution. Enjoy!

Normal use

This is the normal way of using the wp_list_pages function. It uses the ID for the page.

wp_list_pages('include=5');

Extended use 1

The nice thing about this is that you don’t need to know the ID of the page, it looks it up for you. You only need the post name and the ID is stored into the string. Then it writes it on the screen.
$my_id is the string and my_post_or_page_name is the post or page name (which you need to change to your post or page name).

$my_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = 'my_page_or_page_name'");
echo $my_id;

Extended use 2

This is very much like the first one but here I show how to use it. I use wp_list_pages with the string $my_id instead of a number. You only need to replace my_post_or_page_name with your own post or page.

$my_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = 'my_page_or_page_name'");
wp_list_pages('include='.$my_id);

RSS-feed för kommentarer

6 svar till “WordPress – Get ID by post or page name”

  • Peter »
    2009-04-03 @ 19:22

    Thanks, this is just what I was looking for – I need to pull a post id from a post slug for something different, and this did the trick.

    It’s worth noting that post_name actually holds the slug (generally the post name with dashes inserted for non-alphanumeric characters), and post_title actually holds the title of the post.

  • Stephen Lang »
    2010-05-28 @ 11:51

    Thank you – just what I needed for a custom wp_list_pages function I’m making :)

  • Dmitry »
    2010-06-28 @ 15:08

    Also you can use WP function ‘get_page_by_path’.
    For post:
    $p = get_page_by_path(‘my_post_name’,OBJECT,’post’);
    echo $p->ID;
    For page:
    $p = get_page_by_path(‘my_page_name’,OBJECT,’page’);
    echo $p->ID;

  • WordPress hack: Force wp_list_pages() to print current_page_item class | Mark Leong »
    2010-07-17 @ 10:26

    […] http://www.jenst.se/2008/03/17/wordpress-get-id-by-post-or-page-name/ on how to query the database by post/page name to get an […]

  • Philip
    2010-08-12 @ 14:12

    hi and thanks a lot for this post!

    i want to use the Extended use 1 code you describe in your post, but i need to call the categories, is it possible to do this?

    thanks a lot!!!
    Philip

  • Erik »
    2010-12-23 @ 17:24

    Grymt post. Jag har funderat på hur man skulle lösa detta, just nu kör jag med ID, men det kommer bli byte till namn istället :) Åter igen, Tack!