Polylang禁用文章翻译后,多语言站点下如何显示主语言文章?
Got it, let's tackle this problem step by step. You've already disabled translation for blog posts using the pll_get_post_types filter, which works—but now Polylang is filtering out those posts when you're viewing the site in a secondary language because it expects translated versions that don't exist. Here's how to fix that:
Core Solution: Force Main Language Posts in Secondary Language Views
We'll modify the main query to pull your primary language (English) posts when viewing the site in other languages, while keeping the post type untranslatable.
First, add this function to your theme's functions.php file or a custom plugin:
function show_main_lang_posts_in_other_langs( $query ) { // Only target frontend main queries (avoid admin or custom queries) if ( ! is_admin() && $query->is_main_query() ) { // Check if we're on the blog archive or home page if ( $query->is_home() || $query->is_post_type_archive( 'post' ) ) { $current_lang = pll_current_language(); $main_lang = pll_default_language(); // If current language isn't the main one, force query main language posts if ( $current_lang !== $main_lang ) { $query->set( 'lang', $main_lang ); // Disable Polylang's default clause filter to prevent post exclusion remove_filter( 'posts_clauses', 'pll_posts_clauses' ); } } } } add_action( 'pre_get_posts', 'show_main_lang_posts_in_other_langs' );
Fix Single Post Permalinks (Avoid 404s)
When users click a post link from a secondary language view, they might hit a 404 because Polylang expects a translated version. Add this filter to ensure links point directly to the main language post:
function fix_post_permalinks_for_non_main_lang( $permalink, $post ) { if ( $post->post_type === 'post' ) { $current_lang = pll_current_language(); $main_lang = pll_default_language(); if ( $current_lang !== $main_lang ) { // Replace secondary language prefix with main language prefix in the URL $permalink = str_replace( '/' . $current_lang . '/', '/' . $main_lang . '/', $permalink ); } } return $permalink; } add_filter( 'post_type_link', 'fix_post_permalinks_for_non_main_lang', 10, 2 );
Key Notes:
- Replace
enwith your actual main language slug if it's different (check Polylang settings to confirm). - Keep your original
turn_blogposts_translation_offfunction active—this ensures posts still don't show up in Polylang's translation management. - Clear your site cache after adding the code to make sure changes take effect.
内容的提问来源于stack exchange,提问作者Filip

