Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.