【问题标题】:Print WordPress API Call on Page/Post在页面/帖子上打印 WordPress API 调用
【发布时间】:2019-12-05 05:04:06
【问题描述】:

我正在尝试使用以下代码在现有 WP 页面/帖子上的内容之间打印以下句子:

“这是基于 38 条平均得分为 4.9 的评论。” “这是基于平均得分为 4.9 的评论。

我有以下代码:

<script type="text/javascript">
      const url = "https://api.yotpo.com/products/Q6IzQniPhEwgOfDx2C58uKPy5G2OgNnZtPpQpfWI/4379928772/bottomline";

  fetch(url)
    .then(res => res.json())
    .then(json => {
      const data = json.body; // json.response maybe, if it uses that format
      const avg = data.bottomline["average_score"];
      const numReviews = data.bottomline["total_reviews"];
      p.textContent = `This is based on ${numReviews} with an average score of ${avg}`;
    })
    .catch(err => {
      alert("The reviews could not be loaded!");
      console.error(err.message);
    });
</script>

我仍然无法让它正常工作;一些帮助将不胜感激。

【问题讨论】:

  • 我们需要您提供更多代码。例如,还有一个尚未定义的p 变量(至少在您提供的代码中没有)。此外,您需要知道要在其中注入此消息的容器的 id/类。
  • 嗨,Hackerman,感谢您的帮助。如何在页面上而不是在弹出框中打印?
  • @Beccas 我已经在下面发布了答案。
  • @atymic 非常感谢;多么有帮助!它完美地工作!谢谢!!!

标签: php wordpress api curl


【解决方案1】:

在您的模板/帖子中,为 javascript 添加以下内容以填充分数:

<span id="reviews">Loading reviews ...</span>

然后,您可以使用以下 javascript 将分数加载到该标签中:

const url = "https://api.yotpo.com/products/Q6IzQniPhEwgOfDx2C58uKPy5G2OgNnZtPpQpfWI/4379928772/bottomline";

fetch(url)
  .then(res => res.json())
  .then(json => {
    const data = json.response;
    const avg = data.bottomline["average_score"];
    const numReviews = data.bottomline["total_reviews"];
    const textContent = `This is based on ${numReviews} with an average score of ${avg}`;
    document.getElementById('reviews').innerHTML = textContent;
  })
  .catch(err => {
    alert("The reviews could not be loaded!");
    console.error(err.message);
  });

Js fiddle 示例:https://jsfiddle.net/s2zamerk/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多