post_exists() WordPress Function
The post_exists() function is a built-in function in WordPress that allows you to check if a post exists by its title, content, or ID. This function can be useful in a number of situations, such as when you want to check if a post has been created before creating it yourself, or when you want to make sure that a post exists before trying to display it on your website.
post_exists( string $title, string $content = '', string $date = '', string $type = '', string $status = '' ) #
Determines if a post exists based on title, content, date and type.
Parameters
- $title
(string)(Required)Post title.
- $content
(string)(Optional) Post content.
Default value: ''
- $date
(string)(Optional) Post date.
Default value: ''
- $type
(string)(Optional) Post type.
Default value: ''
- $status
(string)(Optional) Post status.
Default value: ''
Return
(int) Post ID if post exists, 0 otherwise.
Source
File: wp-admin/includes/post.php
function post_exists( $title, $content = '', $date = '', $type = '', $status = '' ) { 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' ) ); $post_status = wp_unslash( sanitize_post_field( 'post_status', $status, 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( $status ) ) { $query .= ' AND post_status = %s'; $args[] = $post_status; } if ( ! empty( $args ) ) { return (int) $wpdb->get_var( $wpdb->prepare( $query, $args ) ); } return 0; }
Expand full source codeCollapse full source codeView on TracView on GitHub
Changelog
Version | Description |
---|---|
5.8.0 | Added the $status parameter. |
5.2.0 | Added the $type parameter. |
2.0.0 | Introduced. |