WordPress - 如何获取 JSON 中的所有产品?

WordPress - how to get all products in JSON?

我已经在这几天了。我想从数据库中读取产品,然后 return 将它们 JSON 放在首页,这样我就可以使用它了。问题是我什至不知道如何阅读表格数据库。 我试过制作一个插件,但我也不知道该怎么做。我尝试制作一个单独的 php 脚本并使用全局 $wpdb 但没有响应。任何帮助表示赞赏。

我在 php 脚本中试过这个。

<?php

global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

echo $results;

?>

提前致谢!

<?php
   // gets the global $wpdb variable
   global $wpdb;

   // put the query in its on variable to be able to include your database prefix
   $query = "SELECT * FROM ". $wpdb->prefix ."options WHERE option_id = 1";

   // get database results from the query and stores it as a stdObject
   $results = $wpdb->get_results($query);

   // if something is found, convert the resulting stdObject into a json object
   if ($results) {
      $json = json_encode($results);
      print_r($json);
   }
?>

这应该 return 您的 json 字符串。我 运行 我自己在我的 wordpress 安装上安装它并且它运行顺利。

对我来说,这个 returned:

[{"option_id":"1","option_name":"siteurl","option_value":"https://your_url_here.com","autoload":"yes"}]

编辑

这可以包含在插件中或 the loop

另一个注意事项:如果你打开调试,你会发现你不能将数组作为字符串回显 :) 你需要这样做:

<?php print_r($result); ?>