skip to Main Content

I wanted to create a custom filter query to list all draft posts and be able to display a message that there are no draft posts, if there are none.

I created a loop grid in elementor that lists draft posts but I want a situation where it will display a custom message when there are no posts. Please see below my sample code which does not work. It simply does not run.

function custom_query_filter_show_draft_posts_for_current_user( $query ) {
    // Get the current user's ID
    $current_user_id = get_current_user_id();

    // Set the query to show draft posts authored by the current user
    $query->set('author', $current_user_id);
    $query->set('post_status', 'draft');

    // Check if the query has any draft posts
    $query_result = new WP_Query($query);
    if (!$query_result->have_posts()) {
        echo "You don't have any draft posts.";
    }

    // Restore global post data
    wp_reset_postdata();
}
add_action( 'elementor/query/drafted', 'custom_query_filter_show_draft_posts_for_current_user' );

Would really appreciate any help. Thank you.

2

Answers


  1. Elementor has a special hook elementor/query/query_results which you can use to display some text when a query does not return any results, like this:

    add_action('elementor/query/query_results', function($query) {
        $total = $query->found_posts;
        if ($total == 0) {
            echo '<h1 style="text-align:center;">No results found. </h1>';
        }
    });
    

    Source and more info: GitHub issue

    Hope this helps!

    Login or Signup to reply.
  2. I added an ID to my loop grid element and placed the following code snippet in an HTML element directly below it with the following code

    <div id="message"></div>
    
    <script>
    jQuery(document).ready(function($) {
        // Check if the element with the ID "events" does not exist
        if ($('#events').length == 0) {
            // If the element exists, output the text
            $('#message').text('No posts found.');
        }
    });
    </script>
    

    Replace #events in the code with the id of your loop grid element.

    This snippet will output the text "No posts found." if the id #events is not found.

    Hopefully, Elementor add this feature in the future.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search