Custom Query Filter – Elementor and ACF

Home » Snippets » Custom Query Filter – Elementor and ACF
0

Created with:

Visibility: 

public

Creator: Daniel Ratcliffe

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php

// SEE HERE: https://developers.elementor.com/docs/hooks/custom-query-filter/#Using_the_Custom_Filter

function my_query_by_tutor( $query ) {
    
    // Check if it's the case studies CPT single page
    if ( is_singular( 'case-study' ) ) {
        
        // Get the selected tutor ID from the custom field
        // In ACF this is 'Post Object' field, with a Return Format of 'Post ID' 
        $selected_tutor_id = get_post_meta( get_the_ID(), 'tutor', true );

        // Check if a tutor is selected
        if ( $selected_tutor_id ) {
            // Modify the query to display only the selected tutor
            $query->set( 'post__in', array( $selected_tutor_id ) );
        } else {
            // If no tutor is selected, set the query to return no posts
            $query->set( 'post__in', array( 0 ) );
        }
    }
}
add_action( 'elementor/query/tutor_select', 'my_query_by_tutor' );
				

This code modifies the query in an Elementor loop grid to display the selected post (loop item) from an ACF dropdown. The ACF dropdown is populated with Posts from another CPT.

The example displays the selected tutor as a loop item within a case study. If a tutor is not selected, the loop item will not be displayed at all on the case study page.

Ref: https://developers.elementor.com/docs/hooks/custom-query-filter/#Using_the_Custom_Filter

Register an account to save your snippets or go Pro to get more features.