【问题标题】:WordPress - how to get all products in JSON?WordPress - 如何以 JSON 格式获取所有产品?
【发布时间】:2021-03-27 10:26:42
【问题描述】:

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

我在 php 脚本中试过这个。

<?php

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

echo $results;

?>

提前谢谢你!

【问题讨论】:

    标签: php database wordpress wordpress-database


    【解决方案1】:
    <?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);
       }
    ?>
    

    这应该返回您的 json 字符串。我自己在我的 wordpress 安装上运行它,它运行顺利。

    对我来说,这返回了:

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

    编辑

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

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

    &lt;?php print_r($result); ?&gt;

    【讨论】:

    • 对我来说它没有返回任何东西,这段代码应该写在任何 php 脚本中还是作为插件编写?请帮助我,因为我不知道如何解决这个问题。
    • 对不起,回复晚了,我现在才有更多空闲时间,您是否知道如何获取查询结果并在主页 javascipt 中使用它?基本上如何在外面的另一个函数中让对象脱离循环。
    猜你喜欢
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2017-07-06
    • 2021-08-01
    相关资源
    最近更新 更多