Skip to content

Instantly share code, notes, and snippets.

@phlbnks
Created December 21, 2016 15:27
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 phlbnks/14419bf9ecd4fa7f91e34e064f2db54a to your computer and use it in GitHub Desktop.
Save phlbnks/14419bf9ecd4fa7f91e34e064f2db54a to your computer and use it in GitHub Desktop.
Get a list of terms from a shared taxonomy that are used on a particular post type only
<?php ?>
<label for="filter-country">Country</label>
<select id="filter-country" class="form-control" name="country">
<option selected="" value="">All countries</option>
<?php
if ( false === ( $cptcountries = get_transient( 'cpt_countries' ) ) ) {
global $wpdb;
$cpt_countries = $wpdb->get_col( "select distinct term_taxonomy_id from $wpdb->term_relationships where object_id in ( select ID from $wpdb->posts where post_type='cpt' )" );
$cptcountries = get_terms( array( 'taxonomy' => 'country', 'include' => $cpt_countries ) );
if ( ! empty( $cptcountries ) && ! is_wp_error( $cptcountries ) ) {
set_transient( 'cpt_countries', $cptcountries, 4 * HOUR_IN_SECONDS );
}
}
if ( ! empty( $cptcountries ) && ! is_wp_error( $cptcountries ) ) {
foreach ( $cptcountries as $country ) {
echo '<option ' . selected( $cptcountry, $country->slug ) . ' value="' . esc_attr( $country->slug ) . '">' . esc_html( $country->name ) . '</option>';
}
}
?>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment