简体   繁体   中英

How to use jQuery in WordPress shortcode?

I want to show this jquery variable's value into WordPress shortcode . I already tried but not working.

Jquery code:

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

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

  //alert(post_id);

}); 

PHP Code:

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

It's a bit more complicated than you might think. What you have isn't going to work because PHP processes on the server and jQuery runs in the clients browser.

A potential solution could be.. on button click send the variable ( post_id ) via an AJAX request to the server, this would then process and generate the shortcode html which will then return the html for you to use in your JS.

Below is an example of what I mean...

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.');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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