Skip to content

Instantly share code, notes, and snippets.

@delputnam
Last active August 4, 2018 09:22
Show Gist options
  • Save delputnam/5592113 to your computer and use it in GitHub Desktop.
Save delputnam/5592113 to your computer and use it in GitHub Desktop.
Quick check to determine if a WordPress post exists using the post_name (slug) and post_type (defaults to 'post'). Returns the post ID if found, or 0 (zero) if not found.
/**
* Determine if a post exists based on post_name and post_type
*
* @param $post_name string unique post name
* @param $post_type string post type (defaults to 'post')
*/
function post_exists( $post_name, $post_type='post' ) {
global $wpdb;
$query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
$args = array();
if ( !empty ( $post_name ) ) {
$query .= " AND post_name LIKE '%s' ";
$args[] = $post_name;
}
if ( !empty ( $post_type ) ) {
$query .= " AND post_type = '%s' ";
$args[] = $post_type;
}
if ( !empty ( $args ) )
return $wpdb->get_var( $wpdb->prepare($query, $args) );
return 0;
}
@campusboy87
Copy link

Hello! For this, there is a function get_page_by_path () :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment