post_exists

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

Description

(int) post_exists( (string) $title, (string) $content = '', (string) $date = '' ); 

Returns (int)

Post ID if post exists, 0 otherwise.

Parameters (3)

0. $title (string)
The title.
1. $content — Optional. (string) => ''
Post content
2. $date — Optional. (string) => ''
Post date

Usage

  1. if ( !function_exists( 'post_exists' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/post.php'; 
  3.  
  4. // The title. 
  5. $title = ''; 
  6.  
  7. // Optional post content 
  8. $content = ''; 
  9.  
  10. // Optional post date 
  11. $date = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = post_exists($title, $content, $date); 
  15.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/post.php  
  1. function post_exists($title, $content = '', $date = '') { 
  2. global $wpdb; 
  3.  
  4. $post_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) ); 
  5. $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) ); 
  6. $post_date = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) ); 
  7.  
  8. $query = "SELECT ID FROM $wpdb->posts WHERE 1=1"; 
  9. $args = array(); 
  10.  
  11. if ( !empty ( $date ) ) { 
  12. $query .= ' AND post_date = %s'; 
  13. $args[] = $post_date; 
  14.  
  15. if ( !empty ( $title ) ) { 
  16. $query .= ' AND post_title = %s'; 
  17. $args[] = $post_title; 
  18.  
  19. if ( !empty ( $content ) ) { 
  20. $query .= ' AND post_content = %s'; 
  21. $args[] = $post_content; 
  22.  
  23. if ( !empty ( $args ) ) 
  24. return (int) $wpdb->get_var( $wpdb->prepare($query, $args) ); 
  25.  
  26. return 0;