WooCommerce-REST-API-Client-Library icon indicating copy to clipboard operation
WooCommerce-REST-API-Client-Library copied to clipboard

get_by_sku return false instead of error?

Open lawkwok opened this issue 11 years ago • 4 comments

If the get_by_sku function is used and the SKU does not exist on the server, a 404 error code is returned. Would it not be more helpful to return 'false' so the function can also be used to check the existence of a product?

lawkwok avatar Oct 14 '15 17:10 lawkwok

I would recommend not to use get_by_sku at all. It is deprecated in V3 of the WC API because it has some issues. Use the get API instead with a filter: ['filter' => ['sku' => 'my-sku']]. That will return an array of products, of which there will hopefully be either zero or one.

judgej avatar Oct 28 '15 14:10 judgej

I get "No route was found matching the URL and request method" when I try using a filter. Do I have to manually update the path to "wc-api/v3" in class-ac-api-client.php to use this filter?

$filter_sku = array(
    'filter' => array(
        'sku' => $sku
    )
); 
$product = $client->products->get( $filter_sku );

lawkwok avatar Oct 28 '15 17:10 lawkwok

The filter is the second parameter:

$product = $client->products->get( null, $filter_sku );

The first parameter is the ID, which is null because you are not fetching by ID. This is an excerpt from a plugin I've been working on:

            $check_sku = 'sku/which/can-include/slahes';
            $wc_products = $wc_api->products->get(null, array('filter' => ['sku' => $check_sku]));
            if (isset($wc_products->products) && is_array($wc_products->products) && ! empty($wc_products->products)) {
                $wc_product = $wc_products->products[0];
                $product_id = $wc_product->id;
            } else {
                $product_id = null;
            }

Out of this comes the product ID plus the product, or a null product ID if there is no SKU match.

judgej avatar Oct 28 '15 21:10 judgej

Thanks I got it to work! One other thing, do I need to change the API path to v3?

On Oct 28, 2015, at 2:39 PM, Jason Judge [email protected] wrote:

The filter is the second parameter:

$product = $client->products->get( null, $filter_sku ); The first parameter is the ID, which is null because you are not fetching by ID. This is an excerpt from a plugin I've been working on:

        $wc_products = $wc_api->products->get(null, array('filter' => ['sku' => $check_sku]));
        if (isset($wc_products->products) && is_array($wc_products->products) && ! empty($wc_products->products)) {
            $wc_product = $wc_products->products[0];
            $product_id = $wc_product->id;
        } else {
            $product_id = null;
        }

Out of this comes the product ID plug the product, or a null product ID if there is no SKU match.

— Reply to this email directly or view it on GitHub.

lawkwok avatar Oct 29 '15 06:10 lawkwok