Here I’ve written a sql based function for you. By this you’ll get the terms ID with slug and name by passing the parameter’s as an array-
function the_dramatist_get_terms_with_post_meta( $args = array() ) {
global $wpdb;
$default_args = array(
'taxonomy' => 'category',
'meta_key' => '',
'meta_value' => '',
'post_type' => 'post'
);
$param = wp_parse_args( $args, $default_args );
$sql = $wpdb->prepare("SELECT {$wpdb->prefix}terms.term_id AS terms,
{$wpdb->prefix}terms.name AS name,
{$wpdb->prefix}terms.slug AS name,
{$wpdb->prefix}term_taxonomy.taxonomy AS taxonomy,
COUNT({$wpdb->prefix}posts.id) AS posts
FROM {$wpdb->prefix}posts
INNER JOIN {$wpdb->prefix}term_relationships
ON ( {$wpdb->prefix}posts.id = {$wpdb->prefix}term_relationships.object_id )
INNER JOIN {$wpdb->prefix}term_taxonomy
ON ( {$wpdb->prefix}term_relationships.term_taxonomy_id =
{$wpdb->prefix}term_taxonomy.term_taxonomy_id )
INNER JOIN {$wpdb->prefix}terms
ON ( {$wpdb->prefix}term_taxonomy.term_id = {$wpdb->prefix}terms.term_id )
INNER JOIN {$wpdb->postmeta} AS PM ON ({$wpdb->posts}.ID = PM.post_id)
WHERE {$wpdb->prefix}term_taxonomy.taxonomy = '%s'
AND {$wpdb->prefix}posts.post_type="%s"
AND (PM.meta_key = '%s' AND PM.meta_value="%s")
GROUP BY terms
ORDER BY posts DESC",
array(
$param['taxonomy'],
$param['post_type'],
$param['meta_key'],
$param['meta_value'],
)
) ;
return $wpdb->get_results($sql);
}
Use this function like-
$terms = the_dramatist_get_terms_with_post_meta(
array(
'meta_key' => 'property_channel',
'meta_value' => 1,
'post_type' => 'property',
'taxonomy' => 'property-city'
)
);
Now you’ll get the data as an array of objects. You can do a print_r
on that $terms
variable to understand structure of the returned data of the function. The run a for
loop or a foreach
loop to organize the data.
Hope that helps.