Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active March 13, 2022 03:41
Show Gist options
  • Save RadGH/9ee5d3472f19644bf72ee8817c8b2516 to your computer and use it in GitHub Desktop.
Save RadGH/9ee5d3472f19644bf72ee8817c8b2516 to your computer and use it in GitHub Desktop.
WordPress get_terms replace INNER JOIN with STRAIGHT_JOIN using filters
<?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;
}
@Edi80
Copy link

Edi80 commented May 31, 2020

Hi,
Thank you for that code, please can you tell me where to put it, in functions.php of my wordpress theme right?

@RadGH
Copy link
Author

RadGH commented Jun 1, 2020

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.

@rtpHarry
Copy link

thanks for this, btw the function name doesn't match the one used in the add/remove filter

@RadGH
Copy link
Author

RadGH commented Oct 29, 2020

@rtpHarry oops! Thanks for catching that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment