My Blog
Elementor: Custom Query for any Widget (how to make your own related widget)
- September 17, 2024
- -
- General
- -
- nicolas
Good evening.
Those of you who use Elementor, you will surely have found yourself in the situation where an elementor widget that returns items (eg the one that displays the articles or another one, eg for products or items from a custom post type), does not have the return query we want in the options.
That is, we are not satisfied with the results, not by category, not all and sort them by date or name, not anything at all.
There are cases where a customer will ask for something special, for example they can ask to return based on how many people fit in each boat they sell. He may also want to display related articles under an article but choose manually which articles to display.
So I will use the last one as an example (although the custom query logic is understandable for all):
How to make your own widget that displays selected related items.
We have the case of a custom post type, named rooms, which contains items related to hotel rooms.
Each room, below (before the footer), also displays other related rooms.
The client requested that these be selected manually and not in some dynamic way.
We made with ACF an additional Post Object Field
This, when editing a room, allows you to select other rooms as well, i.e. to define related rooms in each room:
In the related rooms, in the past their appearance was general and random and the only thing you could limit in the query was that they either appear by a certain category, or by name, or by date and all of these in combination:
So this is where elementor comes to help.
According to the following directive: https://developers.elementor.com/docs/hooks/custom-query-filter/ , in any widget there is the "Query ID" option (the field), we can put an ID, so that to manipulate what it will display, using a php function outside the page, eg in wordpress functions.php:
Since we put in a name and saved, the next step was to write the function according to the instructions:
function related_rooms_query( $query ) { $current_room_id = get_the_ID(); $related_rooms = get_field('select_related_rooms', $current_room_id); echo " <script> console.log('Current Room ID:', '".$current_room_id."'); console.log('Related Rooms:', " . json_encode($related_rooms) . "); </script> "; if ( $related_rooms && is_array($related_rooms) ) { $query->set( 'post__in', $related_rooms ); $query->set( 'post_type', 'room' ); } else { $query->set( 'post__in', array(0) ); } } add_action( 'elementor/query/related_rooms_query', 'related_rooms_query' );
For help with the code above, you can ask me, although I think it's pretty self-explanatory.
I have also added js debugging to confirm it is running.
Best regards, Nicolas.
This post is also available in: Ελληνικά