Elementor Pro widgets and templates enable us to add content quickly on WordPress pages.
If you are building a web portal with lot of landing pages, posts & CPT, adding separate templates of Elementor Pro widgets on those landing pages is not a smart idea. One of the better way of adding Elementor Widgets on pages or CPT is by saving them as template, add the query id custom query filter to dynamically set the CPT, category or tag, and add the container using short code or template or better still even use WordPress hook to include the container on any WordPress page dynamically by calling its shortcode.
But in this example we will simply add the Elemontor query id in the Elementor Posts widget and then include it on the CPT detail page using the_content hook to pull and include similar or related posts after the content. You can either pull any type of posts or only a specific type using the following code.
For example, this custom query filter ‘get_posts_by_category’ will get the current post category and pull the other posts from the same category or from a specific CPT.
This way, you can simply use the query id to show posts by category dynamically for any post and use the same saved Elementor template.
Simply add the following custom query filter snippet in your theme functions.php or use Code snippet plugin:
add_action( 'elementor/query/get_posts_by_category', function( $query ) {
global $post;
$term_id=0;
$cpt = 'attractions';
$categories = get_the_category($post->ID);
if ( ! empty( $categories ) ) {
$term_id = $categories[0]->term_id;
}
$query->set('post_type', $cpt); // comment it if you want to get all types of posts
if($term_id){
$tax_query = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $term_id,
),
);
}
if($term_id) $query->set( 'tax_query', $tax_query );
$query->set('order', 'DESC');
} );
And here is the gist link for get posts by category snippet:
This will filter the results for the saved Elementor Template but you need to include the template calling its shortcode on your cpt page using the ‘the_content’ hook.
Add Posts Widget Elementor Pro Templates on any child page using the_content hook
function pim_posts_on_child_page( $content ) {
global $post;
$parent_page_id = '5657';// put your parent page id here
if( in_array($parent_page_id, get_ancestors( $post->ID, 'page' ))) {
$level = count(get_post_ancestors( $post->ID )) + 1;
//Posts widget template will be added on 2nd and 3rd level pages excluding parent.
if( in_array($level, array(2, 3)) ){
//add Posts Widget Elementor Pro Templates block
$before_content .= do_shortcode('[elementor-template id="6359"]');
//add Posts Widget Elementor Pro Templates block
//$after_content .= do_shortcode('[elementor-template id="8373"]');
}
}
return $before_content . $content . $after_content;
}
add_filter( 'the_content', 'pim_posts_on_child_page', 10, 1 );
And here is the gist for adding Posts widget template on child pages of any parent page.
Hope that helps.




