使用Javascript更改wordpress简码

时间:2019-01-30 14:24:40

标签: javascript wordpress shortcode

假设我在一个页面(而不是帖子)中有一个wordpress简码,例如[display id="144,145,146"],并且我想在页面中添加一个链接,例如“单击此处以按视图排序”,因此我可以单击链接和javascript函数可以更改简码,并放置不同的ID。可能吗?

1 个答案:

答案 0 :(得分:2)

如果不使用AJAX,这是不可能的。除非,您在加载之前先加载所有不同的短代码选项。

预加载简码:

$('#change-shortcode').on('click', function() {
  $('.shortcode-container').toggleClass('hidden');
});
.hidden {
  display: none;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shortcode-container">[display id="144,145,146"]</div>
<div class="shortcode-container hidden">[display id="147,148,149"]</div>

<br/><br/>

<a id="change-shortcode">Click Here</a>

使用AJAX获取短代码:

// Add the "fetch_shortcode" AJAX action.
add_action('wp_ajax_nopriv_fetch_shortcode', 'fetch_shortcode');
add_action('wp_ajax_fetch_shortcode', 'fetch_shortcode');


function fetch_shortcode() {
  if (isset($_POST['ids'])) {
    $ids = implode(',', $_POST['ids']);

    // ob_start and ob_get_clean will prevent the shortcode from displaying and instead will return the value to the $html variable.
    ob_start();
    do_shortcode('[display id="' . $ids . '"]');
    $html = ob_get_clean();

    wp_send_json_success($html);
  }
}

在前端,您将拥有:

<div id="shortcode-container">[display id="144,145,146"]</div>

<br/><br/>

<a id="change-shortcode">Click Here</a>

<script>
  $('#change-shortcode').on('click', function() {
      // This is where you get to use the 'fetch_shortcode' action name that you created above.
      data = {
        ids: [147, 148, 149],
        action: 'fetch_shortcode'
      };

      $.ajax({
        url: "<?php echo admin_url('admin-ajax.php') ?>",
        method: "POST",
        data: data
      }).done(function(response) {
        $('#shortcode-container').html(response.data);
      });
  });
</script>