Skip to content

Instantly share code, notes, and snippets.

@jpSimkins
Forked from matheuseduardo/get-page-by-slug.php
Last active March 7, 2018 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpSimkins/b264881d3e789ec44003635f40d727cc to your computer and use it in GitHub Desktop.
Save jpSimkins/b264881d3e789ec44003635f40d727cc to your computer and use it in GitHub Desktop.
get_page_by_slug - wordpress
<?php
/**
* Retrieve a page given its slug.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $page_slug Page slug
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* Default OBJECT.
* @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
* @return WP_Post|null WP_Post on success or null on failure
*/
function get_page_by_slug( $page_slug, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
if ( is_array( $post_type ) ) {
$post_type = esc_sql( $post_type );
$post_type_in_string = "'" . implode( "','", $post_type ) . "'";
} else {
$post_type_in_string = esc_sql( $post_type );
}
$sql = $wpdb->prepare( "
SELECT ID
FROM $wpdb->posts
WHERE post_name = %s
AND post_type IN ($post_type_in_string)
", $page_slug );
$page = $wpdb->get_var( $sql );
if ( $page )
return get_post( $page, $output );
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment