Last active
August 29, 2015 14:17
-
-
Save jazzsequence/3356d427b0067a840285 to your computer and use it in GitHub Desktop.
get post by name
This file contains 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 | |
/** | |
* Helper function to get a specific page by a page slug | |
* | |
* @param string $slug The slug to look for | |
* @param string $type What data you want returned. Takes anything that would be | |
* in a WP_Post object. Defaults to the full post object | |
* @link https://wordpress.org/support/topic/how-to-check-if-page-exists?replies=8#post-466937 | |
* @link http://stackoverflow.com/questions/14979837/wordpress-query-single-post-by-slug | |
*/ | |
function wds_get_post_by_name( $slug = '', $type = '' ) { | |
$post = get_posts( array( | |
'name' => $slug, | |
'post_type' => 'page', | |
'post_status' => 'publish', | |
'numberposts' => 1 | |
) ); | |
if ( is_wp_error( $post ) ) { | |
return false; | |
} | |
if ( '' == $type ) { | |
return $post[0]; | |
} | |
return $post[0]->$type; | |
} | |
// syntax: | |
// $post_object = wds_get_post_by_name( 'some-slug' ); | |
// $post_id = wds_get_post_by_name( 'some-slug', 'ID' ); | |
// $post_title = wds_get_post_by_name( 'some-slug', 'post_title' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment