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

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;
}

You are missing a function parameter. Throw a null in for the second optional paramter $output and this function should work for you.

get_page_by_title('My post title', null, 'customposttype');

I just ran into the same issue and adding the null fixed it for me.


I tend to shy away from direct DB queries. Instead, I use the WP_Query object to parse things for me.

This is, basically, a function I use in one of my themes to get a post based on a given slug:

function get_post_id( $slug, $post_type ) {
    $query = new WP_Query(
        array(
            'name' => $slug,
            'post_type' => $post_type
        )
    );

    $query->the_post();

    return get_the_ID();
}

This will create a query using the WP API to fetch a post of a specific type with a given slug, will run the regular loop functions on the result, and return the ID of the post. You could also use it to return the entire post by modifying the function a bit, but that's up to you.