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;
}
@cbuchler
Copy link

Great idea @delputnam!

You can even make this function more liteweight by using get_post_status

<?php 
/** Determine if post exists or not **/
function prefix_post_exists($ID){
 if(get_post_status($ID) === FALSE){
  // post is not existing
 }else{
  // post exists
 }
}
?>

get_post_status either returns said status of post or false if it doesn't exist.

ref: https://codex.wordpress.org/Function_Reference/get_post_status

@widoz
Copy link

widoz commented Jan 20, 2016

@cbuchler get_post_status doesn't work if you want to check if a post exists before using wp_insert_post to prevent duplicated posts. Or I'm wrong?

@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