在 if 语句中调用脚本 WordPress

我正在尝试使用 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; ?>


有什么解决办法吗?


白板的微信
浏览 83回答 1
1回答

慕莱坞森

我的假设是代码不起作用是因为脚本代码是在 DOM 树准备好之前添加(并因此运行)的。因此,它必须被包装在一个window.onload处理程序(或 jQuery 的$(document).ready();)中。另外,为每种语言复制并粘贴 JS 代码也不是很漂亮。有一个更干净的解决方案:将代码放入 .js 文件中使用 JS 对象来翻译文本将脚本排队,然后使用wp_localize_script()它像这样:&nbsp;my_cart.jswindow.onload = function () {&nbsp; const cartBtn = document.querySelector('.cart button');&nbsp; const formCart = document.querySelector('div.product.elementor form.cart');&nbsp; var newBtn = document.createElement('a');&nbsp; newBtn.innerHTML = "<h1>"+cart_localize.back_to_shop+"</h1>";&nbsp; newBtn.classList.add('cart-custom-link');&nbsp; newBtn.setAttribute("href", "/shop-uk/");&nbsp; cartBtn.addEventListener('click', function() {&nbsp; &nbsp; formCart.appendChild(newBtn);&nbsp; &nbsp; console.log('click');&nbsp; });}接下来,在 PHP 中,将脚本排入队列,如下所示:function load_localized_scripts() {&nbsp; $cart_localize = array(&nbsp; &nbsp; 'back_to_shop' => 'Back to shop', // default&nbsp; );&nbsp; if (pll_current_language() == 'uk') {&nbsp; &nbsp; $cart_localize['back_to_shop'] = 'Повернутися до магазину';&nbsp; }&nbsp; if (pll_current_language() == 'de') {&nbsp; &nbsp; $cart_localize['back_to_shop'] = 'Zurück zum Shop';&nbsp; }&nbsp; wp_enqueue_script('my-cart', plugin_dir_url( __FILE__ ) . 'js/my_cart.js');&nbsp; wp_localize_script('my-cart', 'cart_localize', $cart_localize);&nbsp;}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__():&nbsp; &nbsp; $cart_localize['back_to_shop'] = pll__('back_to_shop');我不会在这里完全介绍这一点,因为我不确定这是否符合您想要管理翻译的方式。
打开App,查看更多内容
随时随地看视频慕课网APP