Coding, Tech and Developers Blog
I recently came across the requirement to have two separate pages on a website that were supposed to display different sets of blog posts as a gallery, all of them being deployed on a single WordPress instance. To solve this issue, I dove into custom queries in WordPress and how to hook them up with Elementor blocks.
Let me share with you how this works:
Image the situation in the following figure. You have a website hosted in a WordPress instance with a set of posts. Now on two different pages of that website, you want to embed the Posts block of Elementor, which can be used to display a gallery-like representation of your posts.
By default, the Posts block will use the total collection of available posts on your site and display them according to your settings, e.g., the latest six posts sorted by date. But how can the input collection of this block be customized to filter items based on your own criteria?
In order to create a custom query for the Posts block, we need to be able to create little, reusable code snippets in WordPress. In order to do this, go to your plugins panel, install and activate WPCode as a new plugin.
After successful installation, the Snippets panel appears in your WordPress administration dashboard. From there, add a new code snippet give it a unique name and insert the following PHP code:
function filterByTagWriting( $query )
$query->set( 'tag', ['writing'] );
add_action( 'elementor/query/filterByTag_writing', 'filterByTagWriting');
In this example, we are declaring a method callback that receives a query object and applies a filter on that query. Here, the query will include all items that are tagged with writing.
In the following line of code, this callback is registered with the name
filterByTag_podcast, which enables other WordPress components to refer to and use it. The second parameter in the
add_action call represents the name of the method that was declared above.
Repeat this process for as many different filters as you want. You can either have separate code snippets for each of them or define them all in a single one.
Since the registration is performed globally, both the registration name and the method callback name must be unique!
Go to the page, that contains the Elementor Posts block, and open the Query pane. In there, insert the name of the custom query that was defined in the code snippet.
Finally, all there is left to do is go to your posts page in the WordPress dashboard and throw all of your relevant tags onto them. You can do that using the Quick Edit for each post on this page.
With this done, your different Post blocks should display only the items you want them to show.
You can change this recipe to work for other properties than tag, too. And the same procedure will also work for non-Elementor blocks. Feel free to experiment!
Was this helpful? What type of query are you using for this?
Be the first to know when a new post was released