Created
June 13, 2019 02:12
-
-
Save RadGH/8fb9941f6a01a3f222a1620807f5ee45 to your computer and use it in GitHub Desktop.
WordPress: Get all terms used by the given post ids
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 | |
| /** | |
| * Returns an array of terms used by the list of post IDs.= | |
| * By default returns an array of arrays, each with the keys: term_id, slug, name, term_taxonomy_id | |
| * You can get an array of single values by changing $return to one of: term_id, slug, name, term_taxonomy_id | |
| * | |
| * @param $post_ids | |
| * @param $taxonomy | |
| * @param string $return | |
| * | |
| * @return array | |
| */ | |
| function dtl_faq_get_terms_for_post_ids( $post_ids, $taxonomy, $return = 'all' ) { | |
| global $wpdb; | |
| // Required values | |
| if ( empty($post_ids) || !$taxonomy ) return array(); | |
| // Ensure post IDs are all value integers | |
| if ( !is_array($post_ids) ) $post_ids = (array) $post_ids; | |
| $post_ids = array_map('intval', $post_ids); | |
| $post_ids = array_filter($post_ids); | |
| // Join post IDs to a comma separated string, and make sure that is escaped | |
| $id_string = esc_sql( implode(', ', $post_ids) ); | |
| // Customize the SELECT statement and change what rows are returned. | |
| $select = "term.term_id, term.slug, term.name, tx.term_taxonomy_id"; | |
| if ( $return == 'term_id' ) $select = 'term.term_id'; | |
| else if ( $return == 'slug' ) $select = 'term.slug'; | |
| else if ( $return == 'name' ) $select = 'term.name'; | |
| else if ( $return == 'term_taxonomy_id' ) $select = 'tx.term_taxonomy_id'; | |
| // Build the SQL query. | |
| $sql = <<<MYSQL | |
| select distinct {$select} | |
| from {$wpdb->term_relationships} tr | |
| inner join {$wpdb->term_taxonomy} tx | |
| on tx.term_taxonomy_id = tr.term_taxonomy_id | |
| inner join {$wpdb->terms} term | |
| on term.term_id = tx.term_id | |
| where | |
| tx.taxonomy = %s | |
| and | |
| tr.object_id in ({$id_string}) | |
| limit 100; | |
| MYSQL; | |
| // Fill in the taxonomy | |
| $sql = $wpdb->prepare( $sql, $taxonomy ); | |
| if ( $return === 'all' ) { | |
| // Get an array of arrays as the result when using "all" | |
| return $wpdb->get_results( $sql, ARRAY_A ); | |
| }else{ | |
| // Otherwise get an array of single values | |
| return $wpdb->get_col( $sql ); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples:
dtl_faq_get_terms_for_post_ids( $post_ids, $taxonomy );
dtl_faq_get_terms_for_post_ids( $post_ids, $taxonomy, 'name' );
dtl_faq_get_terms_for_post_ids( $post_ids, $taxonomy, 'term_id' );