In december 23 someone requested on the Facebook group Global Elementor Community how to display different loops based on the category in the loop grid. Alll comments suggested this was not possible. Challenge accepted.
- First create 1 loop per category and write down the ID of each loop (in my example, the 3 categories are entree, plat and dessert; the corresponding loop ID’s are 330, 342 & 357 –> you can find this in Templates > Saved templates and then click Filter and select Loop Item)
- Then create a custom shortcode function in functions.php
Basically, you retrieve the ID of the current post, then you get the category (taxonomy) of the current post based on its ID, and then you create a condition to display the appropriate loop for a given category.
function customloopshortcode( $atts ) { // If you use default categories, use this //$categories = get_the_category(get_the_ID()); //If you have custom taxonomy, use this and replace type-plat with yours $categories = get_the_terms(get_the_ID(), 'type-plat'); // Check if there are categories if ($categories) { // Display the current category name // echo 'Current Category: ' . esc_html($categories[0]->slug); // and then check what category is assigned to the post and display the corresponding loop if(esc_html($categories[0]->slug) == "entree") { echo do_shortcode( '[elementor-template id="330"]' ); } elseif(esc_html($categories[0]->slug) == "plat") { echo do_shortcode( '[elementor-template id="342"]' ); } elseif(esc_html($categories[0]->slug) == "dessert") { echo do_shortcode( '[elementor-template id="357"]' ); } } } add_shortcode( 'customloop', 'customloopshortcode');
The name of my shortcode function is customloop
- Create a 4th loop
- remove all margins and paddings and add the shortcode widget
- In that widget, call the shortcode function created in functions.php this way [customloop]
Each post with a given category has a different loop displaying its content
without affecting the performance