如何在WordPress短代码中使用jQuery?

时间:2019-04-27 10:21:15

标签: javascript php jquery wordpress-shortcode

我想将此 jquery 变量的值显示为 WordPress简码。 我已经尝试过了,但是没有工作。

jQuery代码:

sudo npm install -g npm

PHP代码:

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

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

  //alert(post_id);

}); 

1 个答案:

答案 0 :(得分:0)

它比您想象的要复杂一些。您拥有的东西将无法工作,因为PHP在服务器上进行处理,而jQuery在客户端浏览器中运行。

可能的解决方案是..单击按钮时,通过AJAX请求将变量(post_id)发送到服务器,然后将处理并生成短代码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.');
}