Is it possible to select against a post’s parent’s fields with WP_Query?

You should use posts_join and posts_where filters to modify JOIN and WHERE clauses.

add_filter( 'posts_join' , 'se333659_posts_join', 20, 2 );
add_filter( 'posts_where' , 'se333659_posts_where', 20, 2 );

function se333659_posts_join( $join, $query )
{
    global $wpdb;

    if ( isset($query->query_vars['_rev_of_publ']) &&
        $query->query_vars['_rev_of_publ'] == '1' )
    {
        $join .= " LEFT JOIN {$wpdb->posts} AS rev_p ON ({$wpdb->posts}.post_parent = rev_p.ID) ";
    }
    return $join;
}

function se333659_posts_where( $where, $query )
{
    global $wpdb;

    if ( isset($query->query_vars['_rev_of_publ']) &&
        $query->query_vars['_rev_of_publ'] == '1' )
    {
        $where .= ' AND rev_p.post_status = \'publish\' AND '.$wpdb->posts.'.post_date <> rev_p.post_date ';
    }
    return $where;
}

How to use:

Changes in the query will be made after passing the _rev_of_publ parameter (name can be changed) to WP_Query.

$args = [
    'post_type'     => 'revision',
    'post_status'   => 'any',     // default value is 'publish'
    '_rev_of_publ'  => 1,
];
$my_query = new WP_Query( $args );

Here you will find more information about using WP_Query.

Leave a Comment