How do I get a post (page or CPT) ID from a title or slug?

I’ve scoured the Codex, failed to get get_page_by_title() to work and am quite surprised that there doesn’t seem to be a standard WP function for this task.

I need to get the ID of any given post/ cpt or page using either the slug of the post/ page title. Ideally I’m looking for the following:

get_post_ID_by_title('My post title', 'customposttype');

What should I be doing?

5 s
5

you can use this function that jumps by google “get post by title”

/**
* Retrieve a post given its title.
*
* @uses $wpdb
*
* @param string $post_title Page title
* @param string $post_type post type ('post','page','any custom type')
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* @return mixed
*/
function get_post_by_title($page_title, $post_type="post" , $output = OBJECT) {
    global $wpdb;
        $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type));
        if ( $post )
            return get_post($post, $output);

    return null;
}

Leave a Comment