[wp-trac] [WordPress Trac] #32526: Tax_Query doesn't working in switch_to_blog()

WordPress Trac noreply at wordpress.org
Thu Mar 5 21:13:24 UTC 2020


#32526: Tax_Query doesn't working in switch_to_blog()
--------------------------------+------------------------
 Reporter:  phill_brown         |       Owner:  (none)
     Type:  defect (bug)        |      Status:  closed
 Priority:  normal              |   Milestone:
Component:  Networks and Sites  |     Version:  4.2.2
 Severity:  normal              |  Resolution:  duplicate
 Keywords:                      |     Focuses:  multisite
--------------------------------+------------------------

Comment (by ciantic):

 I would like to post my workaround here:


 {{{#!php
 <?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 ($taxonomy) 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();
 }}}

 barring any bugs (I did some editing before posting) it should work.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/32526#comment:3>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list