post_exists()
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 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!";
#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. |