PowerPack Documentation

How to Customize Query in Post Widget?

Table of Contents

The query is the core of the PowerPack’s Post Widget. You can customize it to create your own custom query to be used with the widget. Let us see how this can be done.

Step 1: Setup the Custom Filter

1. Add the Post module to the page.

2. Go to Content > Query > Query ID and add an ID for the customized query.

Elementor will use this ID to render a custom Query Filter. For example, if the Query ID is set as my-custom-query then Elementor will render the query filter with the following path – elementor/query/my-custom-filter.

Step 2: Setting up the Query

Customizing the Query will require a little bit of WordPress Query knowledge and coding skills.

1. Open the functions.php file in the active theme.

2. We’ll use the following hook to apply the Query Filter

add_action( 'pp_query_{query_id}', function( $query ) {
    // Modify the posts query here
} );
Example 1:

Filter Posts by Custom Post Type

add_action( 'pp_query_{$query_id}', function( $query ) {
    // Here we set the query to fetch posts with
    // post type of 'custom-post-type1' and 'custom-post-type2'
    $query->set( 'post_type', [ 'custom-post-type1', 'custom-post-type2' ] );
} );

Example 2:

Show Posts after a Specific Date

add_action( 'pp_query_{$query_id}', function( $query ) {
    // Here we set the query to display posts
    // after specific date
    $query->set( 'date_query', array(
    array(
            'after' => 'May 17, 2019', 
        )
    ) ); 
} );

Example 3:

Exclude Posts by ID

add_action( 'pp_query_{$query_id}', function( $query ) {
    // Exclude single posts by ID
    $query->set( 'post__not_in', array( 7, 11 ) );
} );

The action hook provides two parameters:

1. $query – The WP_Query object.
2. $widget – The Current widget object.

You can refer to the following documentation for more details about pre_get_posts filter.

pre_get_posts

You may need to refresh the editor to see the effect of the filter.

Last updated on March 31, 2020