Reputation: 498
I have made a plugin so I can have custom endpoints. Ultimately I want to pull data about my bookable products (woocommerce bookings).
Here is my plugin:
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins',
get_option( 'active_plugins' ) ) ) ) {
// Define constants.
define( 'CUSTOM_ENDPOINTS_PLUGIN_VERSION', '1.0.0' );
define( 'CUSTOM_ENDPOINTS_PLUGIN_DIR', __FILE__ );
// Include the main class.
require plugin_dir_path( __FILE__ ) . '/class-rest-custom-woocommerce-endpoints.php';
}
Then in my main class file:
add_action( 'woocommerce_loaded', 'get_data');
add_action( 'rest_api_init', 'custom_endpoint_first');
function custom_endpoint_first(){
register_rest_route( 'cwe/v1/booking', '/get-data',
array(
'methods' => 'GET',
'callback' => 'get_data')
);
}
function get_data() {
$args = array( 'include' => array(28));
$products = wc_get_products( $args );
return $products;
}
I don't know why it returns an empty array but it has 200 status when I call my custom URL.
Upvotes: 7
Views: 4730
Reputation: 71
Use this snippet to get products in JSON.
public function get_products()
{
$p = wc_get_products(array('status' => 'publish'));
$products = array();
foreach ($p as $product) {
$products[] = $product->get_data();
}
return new WP_REST_Response($products, 200);
}
Upvotes: 7
Reputation: 36
This line
'include' => array(28)
means that you will only get a product with id 28.
Does that product exist?
Is that your intention?
If not, check out this link for some examples
https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query#usage
Upvotes: 0