Support Forum
Support › MB Custom Post Type › Display custom taxonomy with posts having meta_key=xyz and meta_value=1Resolved
Hi all
I have a function calling the display of taxonomies being 'project-taxonomy' related to posts having a post_type="projects"
Until so far, no problem.
But I'd like to display only taxonomies 'project-taxonomy' having posts from post_type="projects" AND a meta_key='display_homepage' with meta_value=1
Is it possible?
The goal being not display the taxonomies which have not posts with this condition (meta_key='display_homepage' with meta_value=1)
My current function is the following:
function projects_get_filters( $taxonomy ) {
$terms = get_terms( $taxonomy );
$count = count( $terms );
if ( $count > 0 ) { ?>
<div class="projects-categories filter-button-group">
<button class="shz-btn--s active" data-filter="*"><?php esc_html_e( 'Tout', 'text-domain' ); ?></button>
<?php foreach ( $terms as $term ) { ?>
<button class="shz-btn--s" data-filter=".<?php echo esc_attr( $term->slug ); ?>"><?php echo esc_html( $term->name ); ?></button>
<?php } ?>
</div>
<?php
}
}
And I call it with:
projects_get_filters( 'project-taxonomy' );
Thank you for your help and ideas
Hi,
I think you can create a custom query to query post with parameter custom fields, see here https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters
then get the term by post ID https://developer.wordpress.org/reference/functions/get_the_terms/
Hi Long and thank you.
I have managed this in a different way but similar. For now it works. I'm going to improve it, especially on the loop part because I'm not confortable with the repeated WP_Query within the loop.
function projects_get_filters_homepage( $taxonomy ) {
$terms = get_terms( $taxonomy );
$count = count($terms);
?>
<div class="projects-categories filter-button-group">
<button class="shz-btn--s active" data-filter="*"><?php esc_html_e( 'Tout', 'text-domain' ); ?></button>
<?php
if ( $count > 0 ){
foreach ( $terms as $term ) {
$args = array(
'post_type' => 'project',
'meta_key' => 'display_homepage',
'meta_value' => '1',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'project-taxonomy',
'field' => 'slug',
'terms' => $term->slug
)
)
);
$my_query = new WP_Query( $args );
if ( (int)$my_query->post_count > 0 ) { ?>
<button class="shz-btn--s" data-filter=".<?php echo esc_attr( $term->slug ); ?>"><?php echo esc_html( $term->name ); ?></button>
<?php
}
}
}
?>
</div>
<?php
}