Skip to content

Instantly share code, notes, and snippets.

@sergeliatko
Created May 29, 2017 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergeliatko/da8f99a1883f3a9c02fef827160f7aee to your computer and use it in GitHub Desktop.
Save sergeliatko/da8f99a1883f3a9c02fef827160f7aee to your computer and use it in GitHub Desktop.
Returns terms from a different taxonomy using common published posts as search criteria. (Ex: get post tags assigned to all posts in a specific category)
<?php
/**
* Returns terms from a different taxonomy using common published posts as search criteria.
* Example: get list of post tags assigned to all posts in a specific category.
*
* @param array $ids Array of source term ids.
* @param string $source Source taxonomy.
* @param string $target Target taxonomy.
*
* @return array
*/
function get_terms_by_common_posts( array $ids = array(), $source = 'category', $target = 'post_tag' ) {
$ids = array_filter( array_map( 'absint', $ids ) );
if( !empty( $ids ) ) {
global $wpdb;
$ids_sql = join( ', ', array_fill( 0, count( $ids ), '%d' ) );
// TODO: create the same thing that will support hierarchical taxonomies.
$sql = "SELECT DISTINCT
tterms.term_id as id
FROM
{$wpdb->posts} as p1
LEFT JOIN {$wpdb->term_relationships} as r1 ON p1.ID = r1.object_ID
LEFT JOIN {$wpdb->term_taxonomy} as stermtax ON r1.term_taxonomy_id = stermtax.term_taxonomy_id
LEFT JOIN {$wpdb->terms} as sterms ON stermtax.term_id = sterms.term_id,
{$wpdb->posts} as p2
LEFT JOIN {$wpdb->term_relationships} as r2 ON p2.ID = r2.object_ID
LEFT JOIN {$wpdb->term_taxonomy} as ttermtax ON r2.term_taxonomy_id = ttermtax.term_taxonomy_id
LEFT JOIN {$wpdb->terms} as tterms ON ttermtax.term_id = tterms.term_id
WHERE (
stermtax.taxonomy = %s
AND sterms.term_id IN ( {$ids_sql} )
AND ttermtax.taxonomy = %s
AND p1.ID = p2.ID
AND p1.post_status = 'publish'
AND p2.post_status = 'publish'
)";
$args = array_merge(
array( $sql ),
array( $source ),
$ids,
array( $target )
);
$query = call_user_func_array( array( $wpdb, 'prepare' ), $args );
$results = $wpdb->get_results( $query );
$terms = empty( $results ) ? array() : wp_list_pluck( $results, 'id' );
$terms = apply_filters( 'get_terms_by_common_posts', $terms, $ids, $source, $target );
return empty( $terms ) ? array() : get_terms( array( 'taxonomy' => $target, 'include' => $terms ) );
}
return array();
}
@sergeliatko
Copy link
Author

Example of getting all post tags assigned to posts in category id = 1
$tags = get_terms_by_common_posts( array(1), 'category', 'post_tag' );

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