WordPress中如何基于Polylang所选语言重定向对应语言感谢页?
解决Contact Form 7结合Polylang的多语言感谢页重定向问题
要实现根据当前语言自动跳转对应版本的感谢页,核心是利用Polylang提供的语言检测函数,结合Contact Form 7的wpcf7_mail_sent钩子修改重定向逻辑,以下是两种可靠的实现方案:
方案一:通过语言代码拼接URL
适合你已经明确各语言感谢页URL结构的场景(默认语言无前缀,其他语言带/语言代码/前缀):
add_action( 'wpcf7_mail_sent', 'redirect_to_poly_thank_you_page' ); function redirect_to_poly_thank_you_page( $contact_form ) { $current_lang = pll_current_language(); // 判断当前是否为默认语言(比如英文),无前缀直接拼接 if ( pll_default_language() === $current_lang ) { $thank_you_url = home_url( '/thank-you/' ); } else { $thank_you_url = home_url( '/' . $current_lang . '/thank-you/' ); } wp_redirect( $thank_you_url ); exit; }
方案二:直接获取对应语言页面的永久链接(更推荐)
通过页面slug获取当前语言版本的感谢页对象,自动获取其永久链接,无需手动拼接URL,适配Polylang的任何URL设置:
add_action( 'wpcf7_mail_sent', 'redirect_to_poly_thank_you_page' ); function redirect_to_poly_thank_you_page( $contact_form ) { // 获取当前语言下slug为'thank-you'的感谢页 $thank_you_page = get_page_by_path( 'thank-you', OBJECT, 'page', pll_current_language() ); // 如果找到对应页面则跳转,否则 fallback 到默认感谢页 if ( $thank_you_page ) { wp_redirect( get_permalink( $thank_you_page ) ); exit; } wp_redirect( home_url( '/thank-you/' ) ); exit; }
额外说明
- 确保Polylang已正确创建各语言版本的感谢页,且每个页面的slug保持一致(比如都是
thank-you) - 如果仅需给特定表单添加重定向,可在函数开头加入表单ID判断:
// 仅ID为123的表单触发重定向,替换为你的表单ID if ( $contact_form->id() !== 123 ) return; - 修改子主题
functions.php前建议先备份文件,避免语法错误导致网站异常
内容的提问来源于stack exchange,提问作者Dmitry
相关产品推荐
相关产品推荐

