Get custom post type by slug

Get custom post type by slug

I recently had a case where I needed to get the post object for a custom post type in WordPress - I had to do this by a slug that the user passed in. There is a function (get_page_by_path) which I initially thought was to find the post object for pages but it actually goes deeper.

The function takes 3 arguments:

  1. The path/slug that you're looking for.
  2. How you want the post to be returned - basically as an array or object.
  3. The post type(s) you want to search through.

So to get the post object (let's call my custom post type 'book') I can just do the following:

$book = get_page_by_path( 'the-cpt-slug', OBJECT, 'book' );

Now that I have the object I can reference it as I would any post object in WordPress:

$book_content = $book->post_content;
// OR
$book_id = $book->ID;

For more information, you can visit the get_page_by_path function reference on WordPress.

Tired of average WordPress hosting? Try Kinsta!