Display custom taxonomy with posts having meta_key=xyz and meta_value=1
Support › MB Custom Post Type › Display custom taxonomy with posts having meta_key=xyz and meta_value=1Resolved
- This topic has 2 replies, 2 voices, and was last updated 3 years ago by
Shemzone.
-
AuthorPosts
-
April 15, 2022 at 11:25 PM #35658
Shemzone
ParticipantHi 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
April 16, 2022 at 6:41 PM #35671Long Nguyen
ModeratorHi,
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/
April 21, 2022 at 4:27 PM #35745Shemzone
ParticipantHi 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 }
-
AuthorPosts
- You must be logged in to reply to this topic.