Is it possible to grab the custom post type post id just only from slug?
As much i know we can get from id by using title. But there can be same title in a custom post type so as slugs are unique is it possible???
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 just want the post id this will do the trick in one line.
url_to_postid( site_url('the_slug') );
url_to_postid
is a very flexible function: you can pass in any kind of permalink/full URL and get the most accurate post-ID for that URL. However, because of the flexible usage it's quite slow (esp. with lot of endpoints/post-types). If you only pass in a slug for a specific post type, it's a lot faster to use get_page_by_path()
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
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 );
post_name
property and category_name
parameter, which should have been slug
and not name
Commented
Dec 3, 2015 at 12:48