Sort your Elementor loop grid by ACF checkbox to prioritise sold items last

David Denedo

David Denedo

Updated on .

Table of Content

A cover image about Elementor Tutorial with easy tips and tricks showing David's face in a round frame to the right

Introduction

Elementor’s Loop Grid is a fantastic tool for displaying dynamic content. But what if you want to customize the order of your grid items based on an ACF checkbox field? This tutorial will show you how to prioritize items marked as “sold” to appear at the end of your Elementor Loop Grid, keeping your content fresh and relevant.

Steps

Create your loop grid template

  • Open your Elementor page editor.
  • Design your Loop Grid template using the elements and styling you prefer.
  • Add the Loop Grid widget to your page (Elementor Pro required).
Elementor Loop Template ordered by date created
Elementor loop grid ordered by post date created

Add a custom query filter

By default, Elementor does not have an option to order by meta field. But fortunately, Elementor has provided a way to apply a custom query filter. You can learn more about it from the Elementor Developer Docs.

Use your preferred method (e.g., code snippets plugin, child theme) to add the following PHP code:

<?php
function dd_query_by_sold_checkbox($query)
{
    // Modify meta_query to use IN to check for "sold" in the array
    $meta_query = [
        "relation" => "OR",
        [
            "key" => "status",
            "value" => "sold",
            "compare" => "NOT IN", // Use NOT IN to exclude arrays with "sold"
        ],
        [
            "key" => "status",
            "compare" => "NOT EXISTS",
        ],
    ];
    
    $query->set("meta_key", "status");
    $query->set("meta_query", $meta_query);
    $query->set("orderby", [
        "meta_value" => "ASC", // Prioritise events without "sold" value (ascending order)
        "date" => "DESC", // Sort by date in descending order as a fallback
    ]);
}

add_action("elementor/query/dd_status_checkbox", "dd_query_by_sold_checkbox");

Apply the query ID to your loop grid

  • Finally, go back to your Elementor loop grid widget settings
  • Under “Content” > “Query” > “Query ID”, enter “dd_status_checkbox
  • Save your changes, and update your page.
Add query id to Elementor loop grid widget under the query section in the content tab

Explanation

  • Meta Query: The PHP code creates a custom query that filters out items marked as “sold” and orders the remaining items first.
  • Orderby: It then sorts the remaining items by the status value (ascending) and date (descending).
  • Query ID: The query ID connects the custom query to your Elementor Loop Grid.

Important Note: Always back up your website before adding custom code.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments