Wordpress - How to get custom post type post id from slug?
You can use get_page_by_path()
- don't let the name fool you, third argument is the post type:
if ( $post = get_page_by_path( 'the_slug', OBJECT, 'post_type' ) )
$id = $post->ID;
else
$id = 0;
If you wait a couple of days, and upgrade to Wordpress 4.4 which will be released the 8th of December (AFAIK), you can use the new post_name__in
parameter in WP_Query
which takes an array of slugs
EXAMPLE
If you need the complete post object
$args = [
'post_type' => 'my_custom_post_type',
'posts_per_page' => 1,
'post_name__in' => ['post-slug']
];
$q = get_posts( $args );
var_dump( $q );
If you only need the ID
$args = [
'post_type' => 'my_custom_post_type',
'posts_per_page' => 1,
'post_name__in' => ['post-slug'],
'fields' => 'ids'
];
$q = get_posts( $args );
var_dump( $q );
If you just want the post id this will do the trick in one line.
url_to_postid( site_url('the_slug') );