繁体   English   中英

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

[英]How to use jQuery in WordPress shortcode?

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

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"]');

它比您想象的要复杂一些。 您拥有的将无法使用,因为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.');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM