Skip to content

Instantly share code, notes, and snippets.

@jesgs jesgs/modify-wp-query.php
Last active Aug 29, 2015

Embed
What would you like to do?
<?php
/**
* Modify WP_Query to return taxonomy fields in post array
*
* @author Jess Green <jgreen AT psy-dreamer.com>
*/
add_filter('posts_orderby', 'taxonomy_orderby');
add_filter('posts_fields', 'taxonomy_archive_select_fields');
add_filter('posts_join', 'taxonomy_archive_join');
/**
* Change orderby parameter for archive-specific loop
*
* @access private
* @global wpdb $wpdb WordPress DB object
* @param string $order_by
* @return string
*/
function taxonomy_orderby($order_by)
{
global $wpdb;
$order_by = "{$wpdb->term_relationships}.term_taxonomy_id, {$order_by}";
return $order_by;
}
/**
* Add fields to SELECT list for loop
*
* @access private
* @global wpdb $wpdb
* @param string $fields
* @param WP_Query $query
* @return string
*/
function taxonomy_archive_select_fields($fields, WP_Query $query = null)
{
global $wpdb;
$fields .= ", {$wpdb->terms}.term_id AS term_ID, {$wpdb->terms}.name AS term_name, {$wpdb->terms}.slug AS term_slug";
return $fields;
}
/**
* Add new INNER JOIN call for forcing taxonomy name and slug to end of post objects
*
* @access private
* @global wpdb $wpdb
* @param string $join
* @return string
*/
function taxonomy_archive_join($join)
{
global $wpdb;
$join .= " INNER JOIN {$wpdb->terms} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->terms}.term_id)";
return $join;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.