Skip to content

Instantly share code, notes, and snippets.

@joehoyle
Created May 1, 2012 17:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joehoyle/2569751 to your computer and use it in GitHub Desktop.
Save joehoyle/2569751 to your computer and use it in GitHub Desktop.
WP_Query advanced post_parent
<?php
/**
* Advanced parent querying with WP_Query
*
* This lets you do somethign like:
*/
$query = new WP_Query( array(
'post_type' => 'attachmemt',
'post_status' => 'publish',
'post_parent' => array(
'post_type' => 'product',
'post_status' => 'draft',
'tax_query' => array( array( 'taxonomy' => 'type', 'terms' => array( 'jacket' ), 'field' => 'slug' ) )
)
) );
/**
* I.e. get all attachments that have post_parents that are prodicts in a given taxonomy.
* Basically, nested queries for post_parent
*
* Below is the hook. Work in progress :)
*/
add_filter( 'parse_query', function( WP_Query $wp_query ) {
if ( empty( $wp_query->query_vars['post_parent'] ) || ! is_array( $wp_query->query_vars['post_parent'] ) )
return;
$wp_query->query_vars['post_parent']['showposts'] = 1;
// Sub queries can not have SQL_CALC_FOUND_ROWS
$wp_query->query_vars['post_parent']['no_found_rows'] = true;
// set some stuff so we can strip it out explicitly
$wp_query->query_vars['post_parent']['order'] = 'DESC';
$wp_query->query_vars['post_parent']['order_by'] = 'date';
// only select IDs as it's used in a subquery
$wp_query->query_vars['post_parent']['fields'] = 'ids';
// WP_Query is crap, so doesn't let you get the query without actually running it (which is why we set showposts = 1 above)
$query = new WP_Query( $wp_query->query_vars['post_parent'] );
unset( $wp_query->query_vars['post_parent'] );
$sql = str_replace( 'ORDER BY wp_posts.post_date DESC LIMIT 0, 1' , '', $query->request );
add_filter( 'posts_where_request', function( $where, $query ) use ( $sql, $wp_query ) {
// blah
if ( $query != $wp_query )
return $where;
global $wpdb;
$where .= " AND $wpdb->posts.post_parent IN (" . $sql . ")";
return $where;
}, 10, 2 );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment