javascript - 使用 Javascript 更改 WordPress 简码

标签 javascript wordpress shortcode

假设我在页面(不是帖子)中有一个 WordPress 短代码,例如 [display id="144,145,146"] 并且我想在页面中添加一个链接,例如“单击此处按 View 排序”,这样我就可以单击链接,并且 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>

关于javascript - 使用 Javascript 更改 WordPress 简码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54442781/

相关文章:

javascript - 一个简单的片段被解析了多少次?

javascript - emscripten window.onload 等效

javascript - Array.prototype.slice.call(arguments) 和 Array.apply(null, arguments) 之间的区别

php - 在 post_updated 操作上获取更新后的元数据

javascript - 在此 WP 模板上通过 MYSQL 数据库上传数百个配置文件?

wordpress - vagrant VCCW环境下无法上传图片到wordpress

WordPress Foreach 只显示一个结果

PHP 通过短代码始终位于页面顶部

php - 具有限制属性的 woocommerce 产品短代码不起作用

javascript - 使用 Select2 Ajax 填充选择选项