Created
May 1, 2012 17:16
-
-
Save joehoyle/2569751 to your computer and use it in GitHub Desktop.
WP_Query advanced post_parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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