[wp-trac] [WordPress Trac] #41796: WP_Term_Query problem using object_ids and number attributes

WordPress Trac noreply at wordpress.org
Thu Jul 30 04:46:52 UTC 2020


#41796: WP_Term_Query problem using object_ids and number attributes
--------------------------+---------------------------
 Reporter:  elvishp2006   |       Owner:  boonebgorges
     Type:  defect (bug)  |      Status:  closed
 Priority:  normal        |   Milestone:  4.9
Component:  Taxonomy      |     Version:  4.8.1
 Severity:  normal        |  Resolution:  fixed
 Keywords:  needs-patch   |     Focuses:
--------------------------+---------------------------

Comment (by raba97):

 This is still a problem in 5.4.2, so I want to leave a work around for
 anyone who needs it.

 Im getting inconsistent results while using `number` + `object_ids` on
 `get_terms` or `WP_Query`.

 When I put `number` = 10, I get 1 result.
 With `number` = 100, I get 34 results.

 This is because, as said in previous responses, the SQL query returns
 duplicated rows.

 The only way I found to fixed this bug, without modifying the core, is to
 force `DISTINCT` through a filter
 {{{#!php
 <?php
 //Add a filter to the `terms_clauses` that forces DISTINCT on the SQL
 function wp_terms_query_force_distinct($clauses, $taxonomies = null, $args
 = null){
     $clauses['distinct'] = 'DISTINCT';
     return $clauses;
 }
 add_filter('terms_clauses', 'wp_terms_query_force_distinct');

 //Your query that uses both objects_ids and number
 $terms_query = new WP_Term_Query( array(
     'object_ids'    => $ids,
     'number'        => 10,
 ) );

 //Remove the filter right after using the query, as to not affect other
 queries
 remove_filter('terms_clauses', 'wp_terms_query_force_distinct');

 }}}

 It feels kinda icky doing it like this, but I need to get this out of the
 way.

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


More information about the wp-trac mailing list