Created
May 12, 2025 10:55
-
-
Save ibrahim-kardi/161af3f89a500f954d257931ae28f647 to your computer and use it in GitHub Desktop.
In stock woocommerce products list API endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action('rest_api_init', function () { | |
register_rest_route('custom/v1', '/in-stock-products', array( | |
'methods' => 'GET', | |
'callback' => 'get_in_stock_products', | |
'permission_callback' => '__return_true', | |
)); | |
}); | |
function get_in_stock_products() { | |
$args = [ | |
'post_type' => 'product', | |
'posts_per_page' => 50, | |
'meta_query' => [ | |
[ | |
'key' => '_stock_status', | |
'value' => 'instock', | |
], | |
], | |
]; | |
$query = new WP_Query($args); | |
$products = []; | |
foreach ($query->posts as $post) { | |
$product = wc_get_product($post->ID); | |
$products[] = [ | |
'id' => $product->get_id(), | |
'name' => $product->get_name(), | |
'price' => $product->get_price(), | |
'url' => get_permalink($product->get_id()), | |
'stock_status' => $product->get_stock_status(), | |
]; | |
} | |
return rest_ensure_response($products); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment