为了账号安全,请及时绑定邮箱和手机立即绑定

在 if 语句中调用脚本 WordPress

在 if 语句中调用脚本 WordPress

PHP
白板的微信 2023-07-01 15:12:25
我正在尝试使用 Polylang 有条件地根据 WordPress 中的语言调用脚本。我可以在 Google Inspector 中看到该脚本,但它不起作用。脚本在定制器中正常工作。代码:<?php if(pll_current_language() == 'en') : ?><script type="text/javascript">    const cartBtn = document.querySelector('.cart button');const formCart = document.querySelector('div.product.elementor form.cart');var newBtn = document.createElement('a');newBtn.innerHTML = "<h1>Back to shop</h1>";newBtn.classList.add('cart-custom-link');newBtn.setAttribute("href", "/shop/");cartBtn.addEventListener('click', function() {   formCart.appendChild(newBtn);   console.log('click');});</script><?php endif; ?><?php if(pll_current_language() == 'uk') : ?><script type="text/javascript">    const cartBtn = document.querySelector('.cart button');const formCart = document.querySelector('div.product.elementor form.cart');var newBtn = document.createElement('a');newBtn.innerHTML = "<h1>Повернутися до магазину</h1>";newBtn.classList.add('cart-custom-link');newBtn.setAttribute("href", "/shop-uk/");cartBtn.addEventListener('click', function() {   formCart.appendChild(newBtn);   console.log('click');});</script><?php endif; ?>有什么解决办法吗?
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

我的假设是代码不起作用是因为脚本代码是在 DOM 树准备好之前添加(并因此运行)的。因此,它必须被包装在一个window.onload处理程序(或 jQuery 的$(document).ready();)中。另外,为每种语言复制并粘贴 JS 代码也不是很漂亮。有一个更干净的解决方案:

  • 将代码放入 .js 文件中

  • 使用 JS 对象来翻译文本

  • 将脚本排队,然后使用wp_localize_script()

像这样: my_cart.js

window.onload = function () {

  const cartBtn = document.querySelector('.cart button');

  const formCart = document.querySelector('div.product.elementor form.cart');

  var newBtn = document.createElement('a');

  newBtn.innerHTML = "<h1>"+cart_localize.back_to_shop+"</h1>";

  newBtn.classList.add('cart-custom-link');

  newBtn.setAttribute("href", "/shop-uk/");


  cartBtn.addEventListener('click', function() {

    formCart.appendChild(newBtn);

    console.log('click');

  });

}

接下来,在 PHP 中,将脚本排入队列,如下所示:


function load_localized_scripts() {

  $cart_localize = array(

    'back_to_shop' => 'Back to shop', // default

  );

  if (pll_current_language() == 'uk') {

    $cart_localize['back_to_shop'] = 'Повернутися до магазину';

  }

  if (pll_current_language() == 'de') {

    $cart_localize['back_to_shop'] = 'Zurück zum Shop';

  }

  wp_enqueue_script('my-cart', plugin_dir_url( __FILE__ ) . 'js/my_cart.js');

  wp_localize_script('my-cart', 'cart_localize', $cart_localize); 

}

add_action('wp_enqueue_scripts', 'load_localized_scripts');

该$cart_localize数组可以包含任意数量的标签键→值对=>文本翻译。它被插入到名为函数第二个参数的 JavaScript 对象中wp_localized_script。然后,您可以使用 JS 在 JS 中访问它cart_localize.key_name。


pll_register_string从技术上讲,您还可以使用命名注册 Polylang 字符串back_to_shop,并使用以下函数轻松插入您在语言 → 字符串翻译下输入的翻译pll__():


    $cart_localize['back_to_shop'] = pll__('back_to_shop');

我不会在这里完全介绍这一点,因为我不确定这是否符合您想要管理翻译的方式。


查看完整回答
反对 回复 2023-07-01
  • 1 回答
  • 0 关注
  • 81 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信