Skip to content

Instantly share code, notes, and snippets.

@jazzsequence
Last active August 29, 2015 14:17
Show Gist options
  • Save jazzsequence/3356d427b0067a840285 to your computer and use it in GitHub Desktop.
Save jazzsequence/3356d427b0067a840285 to your computer and use it in GitHub Desktop.
get post by name
<?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