Skip to content

Instantly share code, notes, and snippets.

@goliver79
Created February 5, 2014 14:38
Show Gist options
  • Save goliver79/8824980 to your computer and use it in GitHub Desktop.
Save goliver79/8824980 to your computer and use it in GitHub Desktop.
[WORDPRESS] Get post by slug
<?php
/*
* get post by slug
*/
function wp_get_post_by_slug( $slug, $post_type = 'post', $unique = true ){
$args=array(
'name' => $slug,
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => 1
);
$my_posts = get_posts( $args );
if( $my_posts ) {
//echo 'ID on the first post found ' . $my_posts[0]->ID;
if( $unique ){
return $my_posts[ 0 ];
}else{
return $my_posts;
}
}
return false;
}
@MaximOrlovsky
Copy link

For now, we have a much easier way to achieve this -- https://codex.wordpress.org/Function_Reference/get_page_by_path

@QuietNoise
Copy link

I understand where Maxim comes from but get_page_by_path serves different purpose. For example it won't work for hierarchical children posts (like pages) where slug and path are different (path would need include slugs from all parents in the hierarchy 'parent_slug/children_slug'). As such above gist is more universal.

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