Search code examples
phpwordpresspluginswpml

Wordpress WPML plugin , get_terms returns data only for current language , i want it return for all available languages?


I'm using WPML Plugin v 4.4.9 and Wordpress v5.6.1

I want the get_terms function to return results for all available languages , ex : for category taxonomy (using some custom meta) , it only returns one result for the current language , how can i make it return result for all languages ?

Ex:

    $args = array(
    'suppress_filter' => true,
    'hide_empty' => false,
    //'meta_query' => $meta_queries,
    );
    
    $terms = get_terms($taxonomy='category',$args);

Solution

  • Here is how ,i'm saving your time here , i've spent 4 damn hours looking through the plugin and wpml forum ...

    # please note is using category taxonomy by default, 
    # you can specify other though , by calling the function with 2 params.
    
    function get_terms_all_langs($taxonomy='category',$args=array()){
    
    #based on menu troubleshooting.php
    #https://developer.wordpress.org/reference/classes/wp_meta_query/
    #https://wpml.org/forums/topic/remove-get_terms-filters/
    
    global $sitepress;
    
    $has_get_terms_args_filter = remove_filter( 'get_terms_args', array( $sitepress, 'get_terms_args_filter' ) );
    $has_get_term_filter       = remove_filter( 'get_term', array( $sitepress, 'get_term_adjust_id' ), 1 );
    $has_terms_clauses_filter  = remove_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ) );
        
    $terms = get_terms( $taxonomy , $args );
        
    if ( $has_terms_clauses_filter ) {
        add_filter( 'terms_clauses', array( $sitepress, 'terms_clauses' ), 10, 3 );
    }
    if ( $has_get_term_filter ) {
        add_filter( 'get_term', array( $sitepress, 'get_term_adjust_id' ), 1, 1 );
    }
    if ( $has_get_terms_args_filter ) {
        add_filter( 'get_terms_args', array( $sitepress, 'get_terms_args_filter' ), 10, 2 );
    }
    
    return $terms;
    }
    

    Sorting the above function results in array[lang] blocks , function example :

    function group_cats_by_lang(){
    
    $args = array('suppress_filter' => true,'hide_empty' => false);
    $all_cats = get_terms_all_langs('category',$args); 
    
    $ro_cats = array();
    $fr_cats = array();
    $en_cats = array();
    
    foreach($all_cats as $cat_obj){
    
    $language_code = apply_filters( 'wpml_element_language_code', null, array( 'element_id'=> (int)$cat_obj->term_id, 'element_type'=> 'category' ) );
    
    if($language_code=="ro"){
    $ro_cats['ro'][] = $cat_obj;
    }
    
    if($language_code=="fr"){
    $fr_cats['fr'][] = $cat_obj;
    }
    
    if($language_code=="en"){
    $en_cats['en'][] = $cat_obj;
    }
    
    
    }
    
    return array($ro_cats,$fr_cats,$en_cats);
    
    }