Seagyn Davis
Get Custom Post Type by Slug

Get Custom Post Type by Slug

Reading time of post 1 min readDate when post was published28 May 2021
Disclosure: Some of the links in this post are affiliate links, meaning that if you click on one of the links and purchase an item, I may receive a commission. All opinions however are my own and I do not accept payments for positive reviews. This is just a little way for me to monetize the time I spend writing for you.

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!

The following companies make my life awesome, maybe they'll make yours awesome too?