【问题标题】:How to use jQuery in WordPress shortcode?如何在 WordPress 短代码中使用 jQuery?
【发布时间】:2019-09-16 16:06:15
【问题描述】:

我想在 WordPress 短代码 中显示这个 jquery 变量的值。 我已经尝试过,但没有工作。

jQuery 代码:

jQuery('.button').on('click', function(){

  var post_id = jQuery(this).attr('data-product_id');

  //alert(post_id);

}); 

PHP 代码:

echo do_shortcode('[product_page id="36"]');

【问题讨论】:

    标签: javascript php jquery wordpress-shortcode


    【解决方案1】:

    这比您想象的要复杂一些。您所拥有的将无法正常工作,因为 PHP 进程在服务器上,而 jQuery 在客户端浏览器中运行。

    一个潜在的解决方案可能是.. 在按钮单击时通过 AJAX 请求将变量 (post_id) 发送到服务器,然后处理并生成短代码 html,然后返回该 html 供您在您的JS。

    下面是我的意思的一个例子......

    jQuery

    $('.button').on('click', function() {
      var $button = $(this);
      var post_id = $button.data('product_id');
      $button.prop('disabled', true); // Disable button. Prevent multiple clicks
      $.ajax({
        url: myLocalVariables.ajax,
        method: 'post',
        data: {
          action: 'render-product-shortcode',
          id: post_id
        }
      }).then(function(response) {
        if (response.success) {
          var $shortcode = $(response.data);
          // Do what ever you want with the html here
          // For example..
          $shortcode.appendTo($('body'));
        } else {
          alert(response.data || 'Something went wrong');
        }
      }).always(function() {
        $button.prop('disabled', false); // Re-enable the button
      });
    });
    

    functions.php

    // Set local JS variable
    add_action('wp_enqueue_scripts', function() {
      wp_localize_script('jquery', 'myLocalVariables', [
        'ajax' => admin_url('admin-ajax.php')
      ]);
    });
    
    // Handle AJAX request
    add_action('wp_ajax_render-product-shortcode', 'render_product_shortcode');
    add_action('wp_ajax_nopriv_render-product-shortcode', 'render_product_shortcode');
    function render_product_shortcode() {
      $product_id = !empty($_POST['id']) ? (int)$_POST['id'] : 0;
      if ($product_id) {
        return wp_send_json_success( do_shortcode('[product_page id="'.$product_id.'"]') );
      }
    
      return wp_send_json_error('No ID in request.');
    }
    

    【讨论】:

    • 感谢您的回复。我用ajax做到了这一点。但这样一来,产品的变体就不起作用了。
    • 所以我想通过jQuery更改产品的id。有可能吗?
    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2013-10-18
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多