phpwordpressloopsshortcodeelementor

Get term id of loop grid item in Elementor


I'm facing a problem that someone already faced but he did not receive an answer here : Elementor Loop Grid widget > post taxonomy | get_queried_object() of the taxonomy iteration

To be clear, I try to filter posts with a server filtering to show only posts included in a chosen taxonomy in a loop grid list of taxonomies.

Indeed, in a loop grid that displays the sub taxonomies of the current archive taxonomy, using this code :

function get_taxonomy_children( $args, $settings, $display_settings ) {
   if ( isset( $settings['term_taxonomy_id'] ) && $settings['term_taxonomy_id'] === 'taxonomy_children' ) {
      $args['term_taxonomy_id'] = '';

      $current_term = get_queried_object();

      if ( isset( $current_term->term_id ) ) {
         $args['parent'] = $current_term->term_id;
      }
   }
   return $args;
}
add_filter( 'elementor/loop_taxonomy/args', 'get_taxonomy_children', 20, 3 );

I then want to show in each element of the category the list of posts associated to this taxonomy.

For example, I have a page which is the archive of the Africa element in my "places" custom taxonomy. Thanks to the previous function, it iterates and gives the ned elements in the loop grid : the direct children of Africa, being Senegal, Ivory Coast, Kenya etc. Then, the goal is to show all the posts in each of these elements. For this, I created a loop grid/post list in elementor, directly nested in the loop grid element of my first sub taxonomy loop grid, and wanted to filter it in server with a function like the one I used before.

However, it seems that the term id of the looped items cannot be accessed, even after multiple tries :

Then, how to properly get the term ID of the loop object?

I haven't found any solution yet.


Solution

  • After digging deep into Elementor Pro's codebase, I discovered that term ID can be retrieved inside a loop item using below code, it can be added inside render function of Elementor custom widget or also inside the shortcode widget, based on that we can output the custom fields added for custom taxonomy.

    global $wp_query;
    
    if ( isset( $wp_query->loop_term ) && isset( $wp_query->loop_term->term_id ) ) {
        $term_id = $wp_query->loop_term->term_id;
    }