WordPress at a glance

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.009029s = very slow | 50000 times = 283.06s = 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: ''

Examples

#1 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.

Code of post exists: wp-admin/includes/post.php WP 5.2.4

<?php
function post_exists( $title, $content = '', $date = '', $type = '' ) {
	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' ) );

	$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( $args ) ) {
		return (int) $wpdb->get_var( $wpdb->prepare( $query, $args ) );
	}

	return 0;
}

Related Functions

From tag: Conditional tags (all)

More from category: Other

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register