Как использовать jQuery в шорткоде WordPress? - PullRequest
1 голос
/ 27 апреля 2019

Я хочу показать значение этой jquery переменной в шорткод WordPress .Я уже пробовал, но не работает.

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

1 Ответ

0 голосов
/ 27 апреля 2019

Это немного сложнее, чем вы думаете.То, что у вас не получится, потому что PHP обрабатывает на сервере, а jQuery запускается в браузере клиентов.

Возможное решение может быть .. при нажатии кнопки отправить переменную (post_id) через AJAXзапрос к серверу, который затем обработает и сгенерирует 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.');
}
...