Skip to content

Instantly share code, notes, and snippets.

@odil-io
Last active August 2, 2022 07:42
Show Gist options
  • Save odil-io/606d66dcc89c8b87cb83c63d47e1373d to your computer and use it in GitHub Desktop.
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.
<?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 );
@odil-io
Copy link
Author

odil-io commented Feb 16, 2022

Usage

$term = array(
	'post_type' => 'POST_TYPE',
);

$terms = get_terms( 'post_tag', $args );

Example output

array(1) {
  [0] => object(WP_Term) {
    ["term_id"]          => int()
    ["name"]             => string()
    ["slug"]             => string()
    ["term_group"]       => int()
    ["term_taxonomy_id"] => int()
    ["taxonomy"]         => string()
    ["description"]      => string()
    ["parent"]           => int()
    ["count"]            => int()
    ["filter"]           => string()
    ["term_order"]       => string()
  }
}

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