Get ID by Page Name
September 2nd, 2008Functions like wp_list_pages() can be really useful in Wordpress but there are things that I don’t like.
For include or exclude pages you need the ID. For me it feels better to use the page name instead, simply because the ID can change but the name does not. I have written a function fix this issue.
The function converts a page name to a page ID. You can use it however you like but in the example I used it with the wp_list_pages() function.
function wt_get_ID_by_page_name($page_name)
{
global $wpdb;
$page_name_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$page_name."'");
return $page_name_id;
}
Call the function in your theme:
<?php wp_list_pages('include='.wt_get_ID_by_page_name('about') ); ?>
If you just need to display the ID of a page, call the function like this instead:
<?php echo wt_get_ID_by_page_name('about'); ?>
To get all new functions/template tags, install my plugin WP Extra Template Tags.
thanks! nice
Thanks. It helps a lot. If you truly want only PAGE results and no POST results mixed in and you have pages and posts which may have the same title, use this:
$page_name_id = $wpdb->get_var(“SELECT ID FROM $wpdb->posts WHERE post_name = ‘”.$page_name.”‘ AND post_type = ‘page’ “);
Wordpress should have an API function for that :/
Hi, I found this example here in the comments:
(http://www.arkinex.com/wordpress/79/current-wordpress-page-name/)
It seems to do the job for getting page names.
Can’t believe WP doesn’t have this in the core.
Especially when some WP peeps start saying how it has caught up Drupal.
Hope that saves some other people the pain for having to id pages.
I was looking for a good 2 hours for a way to do this. Thanks so much!
Tnx, I’ve been using your hack to get this functionality. I notice that the SQL works better for me if I use “… WHERE post_title=’”.$page_name.”‘”);
Nice! Exactly what I needed; seems like this should be in the core.
I’ve been messing round with this for ages. This code works fine if your title contains straight alphanumeric characters. But if your title contains an apostrophe, or an “&” symbol, this code will not work unless using the page slug instead.
Anyone know of a workaround for this?
Thanks!
This is a really nice function, but is it possible to list only the pages you want to include, only 3 of 10 pages of a Wordpress powered site?
Also, is it possible to include title_li= and if so, how?
I would really appreciate this
I’ve been working on this problem all week! Thank you so much!!!
can it used to someting like
thanks for your help