Adding a language rule and showing posts w/ a taxonomy term on its archive page
-
The WordPress website I’m working on is available in two languages using Polylang, en-US and en-PH. I use CPT UI and have a custom taxonomy “subtopic” that is not multilingual. Under “subtopic” are terms like “copyright” and “trademark“.
I intend to do the following:
- If a post with the current term is available in the main language, hide the other translation, but if it is not available in the main language, show it as is (in the secondary language). I am able to do this with the below code added as a snippet:
/*
* Query all posts versions on taxonomy archive page.
*/
function sam_modify_taxonomy_query( $query ) {
if ( function_exists( 'pll__' ) && ! is_admin() && $query->is_tax() ) {
$query->set('tax_query', '');
$query->set('lang', '');
}
}
add_action( 'pre_get_posts', 'sam_modify_taxonomy_query' );- Display only posts with the current taxonomy term on its archive page just like how categories and tags work. [This is the problem]
Below is the code I’m using in the file taxonomy-subtopic.php to achieve both, but I end up getting all posts that are assigned any “subtopic” instead of getting only the posts with the current term (e.g., “copyright” or “trademark“) on the archive page.
When readers visit the “copyright” archive page, for example, they should see only posts that have the term; in the main language or the secondary language if a main language version is not available.
<?php if (have_posts()) : ?>
<header class="header-title-wrapper">
xxx
</header><!-- .header-title-wrapper -->
<h2 class="widget-title"><span>All articles</span></h2>
<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
query_posts(array(
'post_type' => 'post',
'lang' => 'en-PH', // force querying the PH posts
'showposts' => -1,
'tax_query' => array(
array(
'taxonomy' => 'subtopic',
'field' => 'slug',
'terms' => $term->term_id,
'operator' => 'IN'
)
)
)
); ?>
<?php
/* Start the Loop */
while (have_posts()) : the_post(); ?>
<?php global $post;
if($post_id = pll_get_post($post->ID, pll_current_language())) { // get translated post (in current language) if exists
$post = get_post($post_id);
setup_postdata($post);
}?>
<?php
get_template_part('template-parts/content', get_post_format());
?>
<?php endwhile; ?>I would appreciate any advice or explanation that may help fix this. Thank you!
The page I need help with: [log in to see the link]
- You must be logged in to reply to this topic.