Logo Pupungbp.com

Need a WordPress expert help?

How to add Custom Query to Posts Widget and Loop Builder in Elementor

Last Updated: November 15, 2022 | Reading Time: < 1 minute

Elementor has provided a good widget for you to display content from the regular posts or other custom post types. But sometimes, the default options just not enough, the post widget didn’t provide you a complete option.

Luckily, Elementor has provided “query id” for this purpose, it works exactly like the “pre_get_post”. Here’s how:

Add Post Element

After add the element, go to query tab and add query id name.

Query ID

on the other hand to control the query, add this code to the functions.php:

add_action( 'elementor/query/customquery', function( $query ) {
 // Set the custom post type 
$query->set( 'post_type', [ 'flora', 'fauna' ] ); 

// Set for the posts_per_page 
$query->set( 'posts_per_page', 12 ); 
// Display only posts by certain author
$query->set( 'author', 4 );  /* 4 is the ID of the author */

// Set for the custom field 
$meta_query[] = [          
'key' => 'kebutuhan_cahaya',          
'value' => [ 'Sedang' ],          
'compare' => 'in', ];  

$query->set( 'meta_query', $meta_query );

 } );

You can refer to the WP_Query documentation for complete parameters.

Looking for an affordable WordPress solution?

We offer budget-friendly WordPress website development services to meet your needs. Prices start at $10.

Related Posts

7 Responses

  1. Hello. I want to display the posts based on their modified (update) date. But this query is not working properly. Can you write a code for this?

    $query->set( ‘orderby’, ‘modified’ );

  2. Hi, how would you use query->set when wanting to query a post_author. For example by the post_authors user role? Finding it really tough to apply! Your help would be very appreciated.

    1. Thanks for the question, You can use the Author Parameters available:

      $query->set( 'author', 12 );  /* 12 is the ID of the author */
      

      Or

      $query->set( 'author_name', 'pupungbp' );  /* pupungbp is the user_nicename */
      

      You can review the available query for author on WordPress Developer handbook.

      To query posts based on user role, you can review this code, I haven’t test it by my self:

      $users   = new WP_User_Query( array( 'role' => 'role_name' ) );
      $results = $users->get_results();
      
      $user_ids = array();
      foreach( $results as $result ) {
          $user_ids[] = (int) $result->ID;
      }
      
      $user_ids = ! empty( $user_ids ) ? $user_ids : PHP_INT_MAX;
      
      $query->set( 'author__in', $user_ids );
      

      The code above is to retrieve the id’s by user WP_User_Query then the result as array can be use as value to ‘author__in’ query parameter.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.