18

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???

38

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

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 );
  • Nice, but probably a bit intensive to get one post by slug? Why did they add that feature!? – TheDeadMedic Dec 3 '15 at 12:36
  • 1
    @TheDeadMedic Mighty be a bit intensive yes, haven't really tested performance on this, just added as means of an alternative ;-). As to why, I really do not know, looks like one of those nice-to-have-unnecessary things that WordPress is so famous for. The naming convention, IMHO, is also wrong, just like the post_name property and category_name parameter, which should have been slug and not name – Pieter Goosen Dec 3 '15 at 12:48
  • Nice :) wow actually for me its nice update :) – stlawrance Dec 3 '15 at 15:32
  • 1
    @TheDeadMedic There is no time difference between my method and your method. I constantly get between 0.002 and 0.005 seconds to run each of our queries. Also, both methods run 1 query only. ;-) – Pieter Goosen Dec 3 '15 at 17:10
  • 1
    @TheDeadMedic I just meant PHP has less work to do - yes, for sure, totally agree. It is just always nice to know alternatives (although it might sometime not be the best) and having some kind of benchmarks. Enjoy ;-) – Pieter Goosen Dec 3 '15 at 17:34
5

If you just want the post id this will do the trick in one line.

url_to_postid( site_url('the_slug') );
  • 1
    The 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() – Philipp Mar 2 '18 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.