如何检测Ionic 3应用当前语言,动态查询对应语言的WooCommerce分类?
解决方案:根据Ionic应用语言动态查询对应Polylang分类
我之前帮朋友处理过类似的WooCommerce+Polylang+Ionic多语言问题,给你几个从简单到进阶的方案,完美适配你的需求:
方案1:硬编码语言-分类ID映射(快速落地)
这是最直接的方式,适合分类数量不多、变动不频繁的场景:
在Ionic中管理当前语言状态
用Ionic的Storage或者全局服务存储用户选中的语言(比如'en'、'fr'),切换语言时同步更新这个状态。创建语言-分类ID映射表
在你的服务类里定义一个对象,把每种语言对应的分类ID串对应起来:// 示例:英文对应151,152,929,法文对应其他ID private categoryLangMap = { 'en': '151,152,929', 'fr': '153,154,930', 'es': '155,156,931' // 按需添加其他语言 };动态获取对应分类ID并发起请求
先获取当前应用语言,再从映射表中拿到对应的ID串,替换到你的API请求里:async loadCategories() { // 从Storage获取当前语言,默认英文 const currentLang = await this.storage.get('selected_language') || 'en'; // 获取对应分类ID, fallback到英文 const targetCategoryIds = this.categoryLangMap[currentLang] || this.categoryLangMap['en']; // 发起WooCommerce API请求 const categories = await this.http.get( this.config.setUrl('GET', '/wp-json/wc/v2/products/categories?', { per_page: 120, include: targetCategoryIds }) ).toPromise(); // 处理返回的分类数据 console.log('当前语言分类:', categories); }
方案2:自定义WordPress REST端点(灵活进阶)
如果分类数量多、经常变动,硬编码太麻烦,可以在WordPress端写一个自定义REST接口,根据传入的语言参数返回对应分类ID,不用在Ionic里维护映射表:
在WordPress的functions.php中添加自定义端点
利用Polylang的函数(比如pll_get_term())获取对应语言的分类翻译ID:add_action('rest_api_init', function () { // 注册自定义REST路由:/wp-json/custom/v1/category-ids/{lang} register_rest_route( 'custom/v1', '/category-ids/(?P<lang>[a-z]{2})', [ 'methods' => 'GET', 'callback' => 'get_translated_category_ids', 'permission_callback' => '__return_true' // 公开访问,按需调整权限 ] ); }); function get_translated_category_ids($request) { $targetLang = $request->get_param('lang'); // 你的默认语言分类ID(比如英文的ID) $defaultCategoryIds = [151, 152, 929]; $translatedIds = []; // 遍历默认分类,获取对应语言的翻译ID foreach ($defaultCategoryIds as $id) { $translatedTermId = pll_get_term($id, $targetLang); if ($translatedTermId) { $translatedIds[] = $translatedTermId; } } // 返回逗号分隔的ID串 return implode(',', $translatedIds); }在Ionic中调用自定义端点
现在不用硬编码映射表了,直接请求WordPress的自定义接口获取对应语言的分类ID:async getTargetCategoryIds() { const currentLang = await this.storage.get('selected_language') || 'en'; // 请求自定义REST端点 const categoryIds = await this.http.get( `${this.config.baseUrl}/wp-json/custom/v1/category-ids/${currentLang}` ).toPromise(); return categoryIds as string; } async loadCategories() { const targetCategoryIds = await this.getTargetCategoryIds(); // 发起WooCommerce请求,用法和之前一致 const categories = await this.http.get( this.config.setUrl('GET', '/wp-json/wc/v2/products/categories?', { per_page: 120, include: targetCategoryIds }) ).toPromise(); }
注意事项
- Polylang函数可用性:确保在自定义REST端点中Polylang的函数能正常工作,如果遇到问题,可以尝试在回调函数开头添加
pll_load_languages()初始化多语言设置。 - 语言状态同步:Ionic应用切换语言时,记得同步更新
Storage中的selected_language值,确保下次请求能拿到正确的语言参数。 - 权限控制:如果你的分类是私密的,要调整自定义REST端点的
permission_callback,比如用is_user_logged_in()限制登录用户访问。
内容的提问来源于stack exchange,提问作者Victor Logos
相关产品推荐
相关产品推荐

