Archived topic
Filter GB Query Loop based on custom field compared with current post ID
4 replies · Started by John on December 29, 2022
Hi team,
I'm sorry I keep posting, I feel like my inquiries are very similar and yet from the various examples I get, I'm not able to rebuild a different filter because there is always something a bit different. I wish you had some sort of query loop filter code generator :)
I'm hoping this one is easy (for you): On an event post type, I have a custom field that outputs the post ID of another post type (provider). On that Provider page, I would like to build a query loop that is filtered by this field, so that only the event pages for which the custom field return the same ID as the current page are displayed.
The logic is as follows:
1. Each event page has an event_host custom field that outputs the post ID of the provider it is attached to.
2. On each provider page, I want to display a query loop of Events attached to that Provider (i.e. only event pages where event_host equals the current Provider page ID are displayed).
Hopefully that makes sense. How can I compare the value of the event_host custom field to the current page ID and return only the posts that match?
Thank you
Hi John,
Theoretically, the code should look like this:
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
if ( ! is_admin() &&
! empty( $attributes['className'] ) &&
strpos( $attributes['className'], 'cu-query-loop' ) !== false
) {
return array_merge( $query_args, array(
'meta_query' => array(
array(
'key' => 'ADD-PROVIDER-META-SLUG-HERE',
'value' => get_the_ID(),
'compare' => '=',
)
)
) );
}
return $query_args;
}, 10, 2 );
Add cu-query-loop to the class list of the Grid Block of the Query Loop.
Replace ADD-PROVIDER-META-SLUG-HERE with the corresponding post meta field name.
Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets
Thanks Fernando, I will try that as soon as my little one is in bed. In the meantime, you've been helping me so much I feel like I owe you a beer at the very elast. If you accept tips, give me your paypal/cashapp/crypto wallet address and I'll send you one ;)
(not joking)
It works! Thank you very much :)
You're welcome, John! We accept tips here: https://generatepress.com/ongoing-development/
Thank you and Happy New Year! :)
