Check If Post Slug Exists

In the rare cases when you need to check if a post exists by slug, here goes a function to handle that. Note that the slug in WordPress is internally referred as post_name.

Include the function below in your WordPress project. You can add it to your functions.php file in your theme or any file in a custom plugin you’re building.

The function will return the found post ID, if a post with the given slug is found, or otherwise false.

function post_slug_exists( $post_name ) {
	global $wpdb;
	if ( $p = $wpdb->get_row( "SELECT ID, post_name FROM {$wpdb->prefix}posts WHERE post_name = '" . $post_name . "'" ) ) {
		return $p->ID;
	} else {
		return false;
	}
}

Once the function is included, you can use it to check whether a post with a particular slug exists in the database. In my case, I needed to delete the original post before syncing the same post again.

if ( $pid = post_slug_exists( $post->post_name ) ) {
    // Delete this line and do your thing
    wp_delete_post( $pid, true );
}

Keep building!