Last active
August 29, 2015 14:01
-
-
Save scofennell/7a35c59e355d1872a38d to your computer and use it in GitHub Desktop.
WordPress function to alter the main query to grab posts of the attachment type
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 | |
/** | |
* Alter the main query to grab posts of the attachment type | |
* | |
* @param object $query The WP_Query for the current page view | |
*/ | |
function sjf_deh_alter_main_query( $query ) { | |
// we don't want to alter the query in wp-admin | |
if ( is_admin() ) { return; } | |
// we don't want to alter the query if it's not the main query | |
if ( !$query->is_main_query() ) { return; } | |
// furthermore, we only want to do this on the home page | |
if( !is_home() ) { return; } | |
// I happen to be a big fan of the random, in all things. | |
$query->set( 'orderby', 'rand' ); | |
// curate our images such that only our best shots make the cover | |
$tax_query = array( | |
// we've tagged our best photos | |
'taxonomy' => 'post_tag', | |
// the tag we applied to our best photos was "Cover Shot" | |
'terms' => 'cover-shot', | |
// we grab by slug since slugs seem to get broken or changed less frequently than titles or IDs | |
'field' => 'slug', | |
// this is the wp default, but I often like to be verbose/redundant so as to help code readability | |
'operator'=> 'IN' | |
); | |
// add our tax queries into the array of tax_query queries | |
$query->tax_query->queries[] = $tax_query; | |
// add the tax_query query to the current query | |
$query->query_vars['tax_query'] = $query->tax_query->queries; | |
// tell wordpress to only grab posts of the attachment post_type | |
$query->set( 'post_type', 'attachment' ); | |
// because attachments work a little differently than normal posts, we have to tell wordpress to ignore their post_status | |
$query->set( 'post_status', 'any' ); | |
// since we're just doing one large image, we might as well only query 1 | |
$query->set( 'posts_per_page', '1' ); | |
// there's no need to return a value because $query is altered by reference | |
} | |
add_action( 'pre_get_posts', 'sjf_deh_alter_main_query' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment