Last active
March 13, 2022 03:41
-
-
Save RadGH/9ee5d3472f19644bf72ee8817c8b2516 to your computer and use it in GitHub Desktop.
WordPress get_terms replace INNER JOIN with STRAIGHT_JOIN using filters
This file contains hidden or 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 | |
// Step 1. Add the filters surrounding the get_terms (which should be used in your code) | |
add_filter( 'terms_clauses', 'rs_replace_inner_with_straight_joins', 20 ); | |
$terms = get_terms( $args ); | |
remove_filter( 'terms_clauses', 'rs_replace_inner_with_straight_joins', 20 ); | |
// Step 2. Add to functions.php or similar: | |
function rs_replace_inner_with_straight_joins( $pieces, $taxonomies = null, $args = null ) { | |
global $wpdb; | |
$s = 'INNER JOIN ' . $wpdb->prefix; | |
$r = 'STRAIGHT_JOIN ' . $wpdb->prefix; | |
$pieces['join'] = str_replace( $s, $r, $pieces['join'] ); | |
return $pieces; | |
} |
The function (line 7-16) should go in your functions.php. The add/remove filters (line 3 & 5) need to wrap around a get_terms function like I used for #4 as an example.
If you want to affect ALL term queries you will probably run into problems so don't jump straight to that solution.
One important thing to note with STRAIGHT_JOINS is that the joined table is REQUIRED so it must have a value. So if you add a new custom field for example, you need to add a value to all your existing terms or else they won't show up in the query. Even if that query allows the value to be false / blank / not exist.
thanks for this, btw the function name doesn't match the one used in the add/remove filter
@rtpHarry oops! Thanks for catching that
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Thank you for that code, please can you tell me where to put it, in functions.php of my wordpress theme right?