Get ID by post or page name

2010-01-16 @ 14:33

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.


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'");
RSS-feed for comments

2 replys to “Get ID by post or page name”

  • Ivan
    2011-03-01 @ 9:44 f m

    Yes Jens! Yes!
    Are many days I’m looking for this solution!
    It was impossible to find information about what you wrote.!
    From now on you have a new user who follows your website.
    Big Jens.

  • Shaun »
    2012-01-18 @ 5:13 e m

    Really helpful! You wrote a beautiful script for WP programmers.


Leave a reply