1

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

1 Answer 1

1

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.');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I did this with ajax. But in this way the variation of the product does not work.
So I want to change the product's id through jQuery. Is it possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.