Using Custom Query Filter in Elementor in WordPress

Elementor is one of the most popular website builders in WordPress . Elementor website builder allows WordPress users to create and edit websites with a responsive drag-and-drop technique similar to Wix, Metaconex, or Webflow.

In Elementor, both posts widgets and portfolio widgets come with a query control that lets you select specific posts to show in the widget. But sometimes, you need more control over the query. For these situations, there is the custom query filter, which exposes the WP_Query object and allows you to customize the query in a way you want.

Setting Up a Custom Filter in Elementor

In the example below, the query ID is set to my_custom_filter, so when Elementor renders the widget, it will create a custom filter based on the query ID: elementor/query/my_custom_filter

Here comes an image:

Using the Custom Filter

After you have set up the custom query filter, you can use it to modify the query in the same way that the WordPress native pre_get_posts hook lets you modify a query. Using the custom query filter is just like any other WordPress native action hook:

function custom_query_callback( $query ) {
// Modify the posts query here
}
add_action( 'elementor/query/{$query_id}', 'custom_query_callback' );

Examples

Multiple Post Types in a Posts Widget

function my_query_by_post_types( $query ) {
    $query->set( 'post_type', [ 'custom-post-type1', 'custom-post-type2' ] );
}
add_action( 'elementor/query/{$query_id}', 'my_query_by_post_types' );

Conclusion

In this brief example, I have posted a simple example of using Custom Query Filter in Elementor in WordPress.

For most posts from me, please subscribe to our newsletter (coming soon).

Leave a Reply