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';
  • Global. wpdb. $wpdb WordPress database abstraction object.
✈ 1 time = 0.009029s = very slow | 50000 times = 283.06s = extreme 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.';
}

Code of post exists: wp-admin/includes/post.php VER 5.0.3

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

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

	return 0;
}

Related Functions

From tag: Conditional tags (all)

More from category: Other

No comments
    Hello, !     Log In . Register