Posts, Post Types: Improve post_exists() query.

Add `$status` parameter to `post_exists()` to allow developers to specify a post type, date and status to ensure they hit the `wp_posts` table's `type_status_date` index when determining if a post exists.

Props apokalyptik, boonebgorges, brettshumaker, DrewAPicture, MikeHansenMe, peterwilsoncc, whyisjake.
Fixes #34012.


Built from https://develop.svn.wordpress.org/trunk@51027


git-svn-id: http://core.svn.wordpress.org/trunk@50636 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Peter Wilson 2021-05-26 02:17:56 +00:00
parent cc26123e20
commit 885bdb2556
2 changed files with 10 additions and 2 deletions

View File

@ -763,6 +763,7 @@ function get_default_post_to_edit( $post_type = 'post', $create_in_db = false )
*
* @since 2.0.0
* @since 5.2.0 Added the `$type` parameter.
* @since 5.8.0 Added the `$status` parameter.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
@ -770,15 +771,17 @@ function get_default_post_to_edit( $post_type = 'post', $create_in_db = false )
* @param string $content Optional post content.
* @param string $date Optional post date.
* @param string $type Optional post type.
* @param string $status Optional post status.
* @return int Post ID if post exists, 0 otherwise.
*/
function post_exists( $title, $content = '', $date = '', $type = '' ) {
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();
@ -803,6 +806,11 @@ function post_exists( $title, $content = '', $date = '', $type = '' ) {
$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 ) );
}

View File

@ -13,7 +13,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.8-alpha-51026';
$wp_version = '5.8-alpha-51027';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.