1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
/**
 * Retrieves a post id given a post's slug and post type.
 *
 * @uses $wpdb
 *
 * @param string $slug slug of post
 * @param string $post_type post type for post.
 * @return string $id ID of post.
 */
 
function themeblvd_get_id_by_name( $slug, $post_type ) {
	global $wpdb;
	$null = null;
	$slug = sanitize_title( $slug );
	
	// Grab posts from DB (hopefully there's only one!)
	$posts = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND (post_type = %s OR post_type = 'attachment')", $slug, $post_type ));
	
	// If no results, return null
	if ( empty($posts) )
		return $null;
	
	// Run through our results and return the ID of the first. 
	// Hopefully there was only one result, but if there was 
	// more than one, we'll just return a single ID.
	foreach ( $posts as $post )
		if( $post->ID )
			return $post->ID;
	
	// IF for some odd reason, there was no ID in the returned 
	// post ID's, return nothing.
	return $null;
}

// Usage
$post_id = themeblvd_get_id_by_name('sample-page', 'page');
echo $post_id;