Display post translations links on blog, archive page

“Links to the translation of posts” only works for a single post. Some clients asking to add links to translations on blog or archive page for each post.

I encountered two clients so far so I am sharing the script that I am using.

Please add this code in functinos.php file


function wpml_post_languages_in_loop() {
    $post_trid = apply_filters('wpml_element_trid', NULL, get_the_ID(), 'post_' . get_post_type());
    
    if (empty($post_trid)){
        return;
    }
    
    $active_langs = apply_filters( 'wpml_active_languages', NULL, 'skip_missing=0' );
    $translations = apply_filters('wpml_get_element_translations', NULL, $post_trid, 'post_' . get_post_type());
    if (is_array($translations) && !empty($translations)) {
        
        $langs = array();
        foreach ($translations as $translation) {
            if (is_object($translation) && isset($active_langs[$translation->language_code]) && $translation->element_id != get_the_ID()) {
                $langs[] = 'url-to-image';
            }
        }
        
        if (!empty($langs)) {
            echo __('This post is also available in', 'wpml') . ': ' . implode('  ', $langs);
        }
    }
}

Then use this function in the template file to display posts links.


wpml_post_languages_in_loop();

Exclude children terms only from a specific post type from parent taxonomy archive

Please find below code which I tested with custom taxonomy called “hobby” which is assigned to default post type “post” and custom post type “student”. You should change the relative field with below code.


add_action( 'pre_get_posts', 'cyb_pre_get_posts' );
function cyb_pre_get_posts( $query ) {

if( $query->is_tax( 'hobby' ) && $query->is_main_query() && !is_admin() ) {

$children = get_term_by( 'slug', $query->query_vars['hobby'], 'hobby' );
if( $children->parent == 0 ) {

/// find child post entries
$posts_array = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'student',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'hobby',
'field' => 'slug',
'terms' => $query->query_vars['hobby'],
'include_children' => false
))));

$posts_post = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'post',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'hobby',
'field' => 'slug',
'terms' => $query->query_vars['hobby'],
'include_children' => true
))));

$query->query_vars['post__in'] = array_merge($posts_array,$posts_post);
}

}
}