Created
February 5, 2014 14:38
-
-
Save goliver79/8824980 to your computer and use it in GitHub Desktop.
[WORDPRESS] Get post by slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
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
For now, we have a much easier way to achieve this -- https://codex.wordpress.org/Function_Reference/get_page_by_path