How to write a custom query in WP that fetches custom post types filtered by a dynamic taxonomy

Rate this post


I’m a graphic designer that knows nothing about PHP, but I need to get my hands dirty in this particular situation and I need help from the coding gods. I’ve been struggling with this problem quite a bit, reading about it and trying stuff, but I’m probably too noob to figure it out.


I have a WordPress site and I’m using Elementor Pro to build it. I’m using the plugins “CPT-UI” to have my own custom post types, and “CPT-onomies” to be able to use a CPT as a taxonomy for another CPT. From Elementor I can call a custom query if I’m able to write it within the “Snippets” plugin.

The circumstances

That said, I’ll describe exactly what’s going on: I have a “Projects” CPT and a “Designs” CPT, both are CPTs. At the same time, “Projects” is a taxonomy related to “Designs”, this means that I can group many designs that belongs to the same big “Project”. For example, if I’ve designed Coca-Cola’s logo and also designed business cards with that logo, then both designs would be grouped into the taxonomy (which is also a CPT) called “New Coca Identity”. So from within the “New Coca Identity” page (which is actually a dynamic template applied to all “Projects”) I can fetch all designs which have the current loop id (“New Coca Identity” in this case) assigned as their taxonomy.

Should be something like this (I believe)

So this is what I came up with…


// Create the action to call this query from Elementor
add_action('elementor_pro/posts/query/projects_designs_query', function($query)

// Get current meta Query
    $meta_query = $query->get( 'meta_query' );

// If there is no meta query when this filter runs, it should be initialized as an empty array.
    if ( ! $meta_query ) {
        $meta_query = [];

// Append our meta query
    $tax_query[] = [
        'taxonomy' => 'projects',
        'field' => 'term_id',
    $query->set( 'meta_query', $meta_query );
} );



I made it through! I’ll share how I did in case some other person lacking the php knowledge like me lands in the same spot.

add_action('elementor_pro/posts/query/projects_designs_query', function($query)

$post_id = get_the_ID();

$meta_query[] = [
            'post_type' => 'designs',
            'taxonomy' => 'projects',
            'value' => $post_id,
            'compare' => 'in',
$query->set( 'meta_query', $meta_query );
} );

What this achieves is firstly getting the ID of the current post in the loop (which in my case is a Project custom post type). Then it gets all the post (with custom post type Design) that belong to the same project (the current post).

Leave a Reply

Your email address will not be published.

Back to top button