post_exists()WP 2.0.0

Determine if a post with the specified title (post_title) exists. In addition, for the check, you can pass post_content and post_date.

This function expects all values of the passed parameters to be escaped. Ie if you get data from POST request, you need to pass them through wp_slash().

The function works only in the admin panel, if you need it in the front, you need to include the file:

require_once ABSPATH . 'wp-admin/includes/post.php';
1 time — 0.009029 sec (very slow) | 50000 times — 283.06 sec (extremely slow) | PHP 7.1.5, WP 4.9

No Hooks.

Return

Int. Post ID if post exists, 0 otherwise.

Usage

post_exists( $title, $content, $date );
$title(string) (required)
Post title for comparison. Not to be confused with post_name.
$content(string)
The content of the post for comparison.
Default: ''
$date(string)
Post date for comparison, in MySQL format.
Default: ''
$status(string) (с 5.8.0)
Post status.
Default: ''

Examples

1

#1 Check if custom post type [news] exist by title

$fount_post = post_exists( "My Post Title",'','','news' );

echo $fount_post ? "Found post at id #$fount_post" : "Can't find post!";
0

#2 Check if there is a post with the specified title

// require_once ABSPATH . 'wp-admin/includes/post.php';

if( post_exists( 'Date and time formats in WordPress' ) ) {
	echo 'The post with the title "Date and time formats in WordPress" exists.'
}

Notes

  • Global. wpdb. $wpdb WordPress database abstraction object.

Changelog

Since 2.0.0 Introduced.
Since 5.2.0 Added the $type parameter.
Since 5.8.0 Added the $status parameter.

post_exists() code WP 6.5.2

function post_exists( $title, $content = '', $date = '', $type = '', $status = '' ) {
	global $wpdb;

	$post_title   = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
	$post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
	$post_date    = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
	$post_type    = wp_unslash( sanitize_post_field( 'post_type', $type, 0, 'db' ) );
	$post_status  = wp_unslash( sanitize_post_field( 'post_status', $status, 0, 'db' ) );

	$query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
	$args  = array();

	if ( ! empty( $date ) ) {
		$query .= ' AND post_date = %s';
		$args[] = $post_date;
	}

	if ( ! empty( $title ) ) {
		$query .= ' AND post_title = %s';
		$args[] = $post_title;
	}

	if ( ! empty( $content ) ) {
		$query .= ' AND post_content = %s';
		$args[] = $post_content;
	}

	if ( ! empty( $type ) ) {
		$query .= ' AND post_type = %s';
		$args[] = $post_type;
	}

	if ( ! empty( $status ) ) {
		$query .= ' AND post_status = %s';
		$args[] = $post_status;
	}

	if ( ! empty( $args ) ) {
		return (int) $wpdb->get_var( $wpdb->prepare( $query, $args ) );
	}

	return 0;
}