Continuous Integration with WordPress

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 only 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:

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

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

Share on Facebook3Tweet about this on TwitterPin on Pinterest0Share on LinkedIn0Share on Google+0Buffer this pageEmail this to someone

About the author

Seagyn

I'm a passionate "Maker of Things" and build as often as I can. I build things with mainly with PHP and a little Javascript.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *