Skip to content

Instantly share code, notes, and snippets.

@widoz
Last active February 29, 2020 12:47
Show Gist options
  • Save widoz/a135828da49ca70dcb8b5e817a8de167 to your computer and use it in GitHub Desktop.
Save widoz/a135828da49ca70dcb8b5e817a8de167 to your computer and use it in GitHub Desktop.
Wp Post by Name
<?php
/**
* Get post by name
*
* @since 2.0.0
*
* @param string $name The name ( slug ) of the post to retrieve.
* @param string $post_type The post type. Optional. Default to 'post'.
*
* @return WP_Post The post object
*/
function wpPostByName(string $name, string $postType = 'post') {
// Know the post type.
$wpPostType = get_post_type_object($postType);
if (! $wpPostType) {
return new WP_Post(new stdClass());
}
// Set base arguments.
$arguments = [
'post_type' => $postType,
'posts_per_page' => 1,
'ignore_sticky_posts' => true,
];
// Set the properly key for post name.
if (! $wpPostType->hierarchical) {
$arguments['name'] = $name;
} else {
$arguments['pagename'] = $name;
}
$wpPost = new WP_Query( $_args );
if (!$wpPost->found_posts) {
// Must be sure to return always a WP_Post object even with no data.
return new WP_Post(new stdClass());
}
return reset($wpPost->posts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment