-
apinajus
Hi,
I want to retrieve posts based in Custom Fields values but I don’t know how to do it.
Can you be out of help?Thanks
-
Alvind
Hi there,
You may need to use a snippet for that. Can you explain a bit further about how you want to achieve this and which plugin you are using for the custom field?
-
apinajus
Hi,
I am not using any plugin, only the wordpress feature for that.
Essentially I have a given category of posts in which I tag the city for each of one of them (I am using the “tags” feature for another purpose).
therefore I would like to pull the info from this custom field in a query loop.Does it make sense?
-
Alvind
Not sure if I’m getting this right, but from what I understand, you’ve added a custom field to each post, and now you want to display the posts based on a specific value of that custom field. Is that correct?
-
apinajus
Correct!
-
therefore I would like to pull the info from this custom field in a query loop.
I am still not clear, are you talking about the wp tags or the custom field?
If it’s custom field, please check this article: https://docs.generateblocks.com/article/order-query-loop-by-custom-field/
-
apinajus
-
Hi there,
First, add a class to the Grid block inside of the Query Loop:
query-by-city
Then, try this:
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) { // apply filter if loop has class: query-by-city if (! is_admin() && ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'query-by-city' ) !== false) { $query_args = array_merge( $query_args, array( 'meta_query' => array( array( 'key' => 'city', 'value' => 'Wielicka', 'compare' => '=', ) ), ) ); } return $query_args; }, 10, 2 );
Let me know if that works or not 🙂
-
apinajus
Hi Tom,
Thanks for this.
I understand that this function will work only when the value = ‘Wielicka’I do have a bunch of other cities so I was thinking in adding the option as a parameter in the Query Loop menu as shown here
Can it be done?
Thanks
-
Not without it affecting the query, which we don’t want here.
One possibility is to use the Custom Attributes feature in the Grid block.
You could do something like this:
key:
data-city
value: Your ValueThen you could adjust your function:
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) { // apply filter if loop has class: query-by-city if (! is_admin() && ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'query-by-city' ) !== false) { $html_attributes = $attributes['htmlAttributes']; $city = ''; foreach ( $html_attributes as $attribute ) { if ( 'data-city' === $attribute['attribute'] ) { $city = $attribute['value']; } } if ( ! $city ) { return $query_args; } $query_args = array_merge( $query_args, array( 'meta_query' => array( array( 'key' => 'city', 'value' => $city, 'compare' => '=', ) ), ) ); } return $query_args; }, 10, 2 );
- You must be logged in to reply to this topic.