簡體   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