get_id_by_post_name()

2010-01-16 @ 14:53

The 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.

RSS-feed for comments

2 replys to “get_id_by_post_name()”

  • Rama
    2011-01-29 @ 7:19 f m

    Thank you!

    btw, why wordpress does not include this function?

    Reply
  • Aaron
    2011-02-25 @ 9:00 f m

    Agree with Rama. Even get_by_postname would work…good for anti-collision in a plugin.

    Reply

Leave a reply