Skip to content

Instantly share code, notes, and snippets.

@kostiantyn-petlia
Created August 8, 2015 23:32
Show Gist options
  • Save kostiantyn-petlia/2cfd0ff359a6a4630b8e to your computer and use it in GitHub Desktop.
Save kostiantyn-petlia/2cfd0ff359a6a4630b8e to your computer and use it in GitHub Desktop.
function get_post_by_slug($slug, $post_type){
$posts = get_posts(array(
'name' => $slug,
'posts_per_page' => 1,
'post_type' => $post_type,
'post_status' => 'publish'
));
if( !$posts ) {
throw new Exception("NoSuchPostBySpecifiedID");
}
return $posts[0];
}
// get post ID
$post = get_post_by_slug('the_company', 'company');
$id = $post->ID;
// post by ID
$post = get_post( $id );
@krzysiekdrozdz
Copy link

And why don't you use native get_page_by_path function?

https://codex.wordpress.org/Function_Reference/get_page_by_path

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment