Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
// tax_query is not usable in switched blog context:
// https://core.trac.wordpress.org/ticket/32526
switch_to_blog(123);
$taxonomy = "category";
$operator = "in";
$terms = ["news", "blog"];
$tax_query_where = function ($where, $query) use ($terms, $operator, $taxonomy) {
global $wpdb;
$terms_sql = implode(',', array_map(function($v) {
return "'" . esc_sql($v) . "'";
}, $terms));
$tax_sql = "'" . esc_sql($taxonomy) . "'";
$where .= "AND (taxonomy IN ($tax_sql) AND name $operator ($terms_sql))";
return $where;
};
$tax_join = function ($join) {
global $wpdb;
$join .= " LEFT JOIN $wpdb->term_relationships as wtr ON ($wpdb->posts.ID = wtr.object_id) ";
$join .= " LEFT JOIN $wpdb->term_taxonomy as wtt ON (wtr.term_taxonomy_id = wtt.term_taxonomy_id) ";
$join .= " LEFT JOIN $wpdb->terms as wt ON(wtt.term_id = wt.term_id) ";
return $join;
};
add_filter('posts_where', $tax_query_where, 10, 1);
add_filter("posts_join", $tax_join, 10, 1);
$q = new WP_Query(array(
"post_type" => "post",
));
// ... do your thing ...
remove_filter('posts_where', $tax_query_where, 10, 1);
remove_filter('posts_join', $tax_join, 10, 1);
restore_current_blog();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment