'Create custom endpoints for WooCommerce functions
I have this code in my headless WordPress function file
<?php
function list_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);
}
add_action( 'rest_api_init', function(){
register_rest_route( 'shop/v1', '/products', array(
'methods' => 'GET',
'callback' => 'list_products'
));
});
?>
What I need to achieve is to have a safe way to use WooCommerce in a headless WordPress and since hardcoding the user keys inside the client side code is a bad practice I need an alternative way to get WooCommerce products on the front-end.
The code will return an empty array, I'm not sure where the problem is.
I'm noticing that the response from the AJAX call made from the fornt-end to the custom endpoint will return the content of my index.php page. It now contains just a message that will infrom the user that the website is under construction.
I'm using this code in my vue app to make AJAX calls
<script>
import axios from 'axios';
export default {
name: 'Home',
data(){
return {
mediaBaseURL: 'https://www.mycoolsite.it/app/wp-json/wp/v2/media/29',
productsBaseURL: 'https://www.mycoolsite.it/app/wp-json/shop/v1/products',
offers: [],
placeholderImage: ''
}
},
created(){
},
mounted(){
this.LoadMedia();
this.LoadOffers();
console.log(this.offers);
},
methods: {
LoadMedia(){
axios.get(this.mediaBaseURL).then( response => {
console.log(response.data);
this.placeholderImage = response.data.source_url;
}).catch( e => console.log(e) );
},
LoadOffers(){
axios.get(this.productsBaseURL, {
}).then( response => {
console.log(response.data);
}).catch( e => console.log(e) );
}
}
}
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
