Cristian Cutitei
Cristian Cutitei

Reputation: 150

WordPress - how to get all products in JSON?

I ve been at this for a few days now. I want to read the products from the database and return them in a JSON to the front page so I can use it. The problem is i dont even know how to read form db. I ve tried making a plugin but i dont know how to do that either. I ve tried making a separate php script and using global $wpdb but no response. Any help appreciated.

I tried this in a php script.

<?php

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

echo $results;

?>

Thank you in advance!

Upvotes: 0

Views: 1284

Answers (1)

Krist&#243;fer
Krist&#243;fer

Reputation: 95

<?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);
   }
?>

This should return your json string. I ran it myself on my wordpress installation and it worked without a hitch.

For me, this returned:

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

EDIT

This can be included in a plugin or in the loop.

Another note: if you'd turn on debugging you'd see that you can't echo arrays out as a string :) You'd need to do this:

<?php print_r($result); ?>

Upvotes: 1

Related Questions