繁体   English   中英

使用Javascript更改wordpress简码

[英]Change wordpress shortcode with Javascript

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

不使用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>

暂无
暂无

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

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