WordPress.org

Make WordPress Core


Ignore:
Timestamp:
05/26/2021 02:16:01 AM (8 months ago)
Author:
peterwilsoncc
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-admin/includes/post.php

    r50809 r51027  
    764764 * @since 2.0.0
    765765 * @since 5.2.0 Added the `$type` parameter.
     766 * @since 5.8.0 Added the `$status` parameter.
    766767 *
    767768 * @global wpdb $wpdb WordPress database abstraction object.
     
    771772 * @param string $date    Optional post date.
    772773 * @param string $type    Optional post type.
     774 * @param string $status  Optional post status.
    773775 * @return int Post ID if post exists, 0 otherwise.
    774776 */
    775 function post_exists( $title, $content = '', $date = '', $type = '' ) {
     777function post_exists( $title, $content = '', $date = '', $type = '', $status = '' ) {
    776778    global $wpdb;
    777779
     
    780782    $post_date    = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
    781783    $post_type    = wp_unslash( sanitize_post_field( 'post_type', $type, 0, 'db' ) );
     784    $post_status  = wp_unslash( sanitize_post_field( 'post_status', $status, 0, 'db' ) );
    782785
    783786    $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
     
    802805        $query .= ' AND post_type = %s';
    803806        $args[] = $post_type;
     807    }
     808
     809    if ( ! empty( $status ) ) {
     810        $query .= ' AND post_status = %s';
     811        $args[] = $post_status;
    804812    }
    805813
Note: See TracChangeset for help on using the changeset viewer.