【问题标题】:Getting data from WP Query and into a javascript array从 WP Query 获取数据并放入 javascript 数组
【发布时间】:2023-03-29 13:48:01
【问题描述】:

我正在尝试从 WordPress 的 location 帖子类型中查询一组位置,然后将它们设置为 javascript 数组,以便我可以将其与 Google Matrix API 一起使用。我只是不太确定总体上最好的方法。

我可以构造查询,但是如果要在循环中运行它,我不确定我是否只是在某个地方塞入一个变量以获取数据,或者最好的过程是什么。

这是我目前正在尝试做的事情:

    <?php $args = array( 'post_type' => 'locations', 'posts_per_page' => -1);
            $loop = new WP_Query($args); ?>
              <?php if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();
              $title = esc_html( get_the_title() );
              $location = get_field('address');
              ?>
            <?php endwhile; endif; ?>
<script>
var locations = <?php json_encode($the_data_im_trying_to_get) ?>;
//other JS things...
</script>

另一个问题是我也不确定是否也将 ACF 数据与帖子类型数据合并?

我正在研究 query_posts 有点 可能 工作,但话又说回来,我不确定如何获取该帖子类型的所有帖子并从中获取 ACF 数据那也是。

再一次,不完全确定我是否以正确的方式解决这个问题。

【问题讨论】:

    标签: javascript jquery arrays wordpress


    【解决方案1】:
    <script type="text/javascript">
          dataFromQuery  = "<?= base64_encode(json_encode($the_data_im_trying_to_get));?>";
    </script>
    

    您可以尝试上面的代码来获取javascript数组中的数据。

    要解析这个数组,你可以使用下面的代码。

    <script type="text/javascript">
          temp = JSON.parse(atob(dataFromQuery));
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 2023-03-26
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 2017-08-11
      相关资源
      最近更新 更多