Last active
August 4, 2018 09:22
-
-
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.
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
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello! For this, there is a function
get_page_by_path ()
:-)