I have an Elementor Single Post Template for video tutorials. This tutorial has been tagged with a custom taxonomy called ‘Project Focus’ (example: Branding).
At the bottom of the Single Post Template I have an Elementor loop carousel. I would like this carousel to Query the post type of “Portfolio”, by the Project Focus that the current post is tagged with. So, if this particular video tutorial is tagged with ‘Branding’, I would like it to display a carousel filled with ‘Branding’ Portfolio items.
Essentially, I’m looking to fetch Portfolio posts that are related to the current Video post, by Project Focus taxonomy.
I started with the basic query example from Elementor’s documentation. I have that working in basic form, so adding the custom query into Code Snippets and then the query ID into the Loop Carousel is working, if just to query another post type/s.
What isn’t working is the query for taking the current video post’s ‘project focus’ term (such as Branding) and then modifying the query for portfolio items of that identified term.
I’ve gone back and forth with Chat GPT to iron it out around some errors that caused whitescreen or template destruction.
This is the latest I have:
function custom_case_study_query( $query ) {
// Ensure we're only modifying the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Get the current video-tutorial post's project-element term.
$location_terms = wp_get_post_terms( get_the_ID(), 'project_focus' );
if ( ! empty( $location_terms ) && ! is_wp_error( $location_terms ) ) {
// Extract the first term's slug (e.g., 'branding').
$location_slug = $location_terms[0]->slug;
// Log the term we're using for filtering.
error_log( 'Filtering posts by project-element term: ' . $location_slug );
// Modify the query to only show portfolio-item posts tagged with the same project-element.
$query->set( 'post_type', 'portfolio' );
$query->set( 'tax_query', array(
array(
'taxonomy' => 'project_focus',
'field' => 'slug',
'terms' => $location_slug,
),
));
// Exclude the current video-tutorial post (to prevent recursion or conflicts).
$query->set( 'post__not_in', array( get_the_ID() ) );
// Safety: Ensure we have a reasonable number of posts.
$query->set( 'posts_per_page', -1 ); // Retrieve all matching posts.
$query->set( 'no_found_rows', true ); // Skip pagination for performance.
// Log the final query parameters for debugging.
error_log( print_r( $query, true ) );
} else {
error_log( "No terms found or there was an error retrieving project-element terms." );
}
}
add_action( 'elementor/query/newcasequery', 'custom_case_study_query' );
newcasequery is the ID I add into Elementor.
This all sits in Code Snippets.
2