Last active
August 2, 2022 07:42
-
-
Save odil-io/606d66dcc89c8b87cb83c63d47e1373d to your computer and use it in GitHub Desktop.
WordPress: Add support to `get_terms()` to limit results to Terms used by Post Type.
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 | |
/** | |
* Terms_clauses | |
* | |
* Filter the terms clauses. | |
* | |
* @param $clauses array | |
* @param $taxonomy string | |
* @param $args array | |
* @return array | |
**/ | |
function terms_clauses( $clauses, $taxonomy, $args ) { | |
global $wpdb; | |
if ( array_key_exists( 'post_type', $args ) ) { | |
$post_types = $args['post_type']; | |
if ( is_array( $args['post_type'] ) ) { | |
$post_types = implode( "','", $args['post_type'] ); | |
} | |
$clauses['join'] .= " INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id"; | |
$clauses['where'] .= " AND p.post_type IN ('" . esc_sql( $post_types ) . "') GROUP BY t.term_id"; | |
} | |
return $clauses; | |
} | |
add_filter( 'terms_clauses', 'terms_clauses', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Example output