Skip to content

Instantly share code, notes, and snippets.

@RadGH
Last active March 13, 2022 03:41
Show Gist options
  • Select an option

  • Save RadGH/9ee5d3472f19644bf72ee8817c8b2516 to your computer and use it in GitHub Desktop.

Select an option

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

Edi80 commented May 31, 2020

Copy link
Copy Markdown

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

@RadGH

RadGH commented Jun 1, 2020

Copy link
Copy Markdown
Author

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
Copy Markdown

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

@RadGH

RadGH commented Oct 29, 2020

Copy link
Copy Markdown
Author

@rtpHarry oops! Thanks for catching that

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