WordPress at a glance

post_exists() WP 1.0

Determine if a post exists based on title, content, and date

  • 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
$content(string)
Optional post content
Default: ''
$date(string)
Optional post date
Default: ''

Code of post_exists: wp-admin/includes/post.php VER 4.9.8

<?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