get_id_by_post_name()
2010-01-16 @ 14:53The problem
As far as I know there are no function in WordPress that ”converts” a page /post name to an ID.
The solution
The function converts a post / page name to a post /page ID.
function get_id_by_post_name($post_name) { global $wpdb; $id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$post_name."'"); return $id; }
Function call
Call the function somewhere in your theme.
<?php echo get_id_by_post_name('my-post-name'); ?>
Improvements
Do you have any ideas, bugs, features or anything else to improve the code? Write a comment and I’ll look into it.
2011-01-29 @ 7:19 f m
Thank you!
btw, why wordpress does not include this function?
2011-02-25 @ 9:00 f m
Agree with Rama. Even get_by_postname would work…good for anti-collision in a plugin.
2012-08-05 @ 6:45 e m
[…] into a publish id. I’ve had a glance around on the internet and handled to locate this link http://world wide web.devdevote.com/content management systems/wordpress-hacks/get_id_by_publish_tit… which provides the next […]
2012-09-16 @ 8:57 e m
This is very useful. I did not know about ‘get_var’. This is a very quick way to get an specific property of a post/page without having to inspect a post object.