admin管理员组

文章数量:1122832

Closed. This question is off-topic. It is not currently accepting answers.

Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.

Closed 8 months ago.

Improve this question

If I used /wp-json/wc/v3/products I am getting all products, but what if I want to receive only price and quantity, I searched all we web and couldn't find it!

Closed. This question is off-topic. It is not currently accepting answers.

Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.

Closed 8 months ago.

Improve this question

If I used /wp-json/wc/v3/products I am getting all products, but what if I want to receive only price and quantity, I searched all we web and couldn't find it!

Share Improve this question asked Aug 12, 2020 at 17:31 Bassim Bassim 311 silver badge2 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 5

Woocommerce rest API is an extension of WordPress rest API, so you should first check global parameters and specifically "_fields" in the REST API Handbook of Wordpress.org.

I will give you an example of the data that you want, price and quantity, but also the id and the name of the products for the response to be more human friendly.

/wp-json/wc/v3/products?per_page=100&_fields=id,name,regular_price,stock_quantity

The "_fields" attribute is used for every attribute you want to get.

The "per_page" attribute with value of "100" is used to get 100 products which is the max acceptable value of this attribute and if you leave it empty the default is only "10".

Sorry for the 10 months later answer, but I hope that helped you and any other that is facing the same issue.

First of all, sorry for my bad english!

In PHP, after your file_get_contents(home_url().'/wp-json/wc/v3/products'), use json_decode and get your informations like this:

<?php
    $products = json_decode(file_get_contents(home_url().'/wp-json/wc/v3/products'));
    foreach($products as $product){

        echo $product->price;
        echo $product->regular_price;
        echo $product->sale_price;
        
        echo $product->stock_quantity;
    }
?>

You can put a look here for more informations: https://woocommerce.github.io/woocommerce-rest-api-docs/#products

EDIT: If you want stock the price and quantity only with the product, you can do this:

<?php
    $products = json_decode(file_get_contents(home_url().'/wp-json/wc/v3/products'));
    
    $products_array = array();
    foreach($products as $product){
        
        $products_array[] = array(
            'id' => $product->id,
            'price' => $product->price,
            'stock_qty' => $product->stock_quantity,
        );
    }
?>

use or return $products_array...

please try the plugin to Get specific values in Woocommerce Rest API [products]

please see JSON output I am using two extra parameter origin, token but you can set only two parameter for permission consumer_secret , consumer_key only.

/wp-json/wp/v3/products?per_page=100&_fields=id,name,regular_price,stock_quantity

<?php

/**
 * Plugin Name: Custom Woocommerce Rest API Plugin
 * Author: Test Plugin.
 * Author URI: https://www.testplugin.com/
 * Description: Wordpress: Woocommerce rest api dynamic call.
 * Text Domain: woocommerce-rest-api
 *
 * @package woocommerce-rest-api
 */

defined('ABSPATH') || die('you do not have access to this page!');

defined('PLUGIN_DIR') ? '' : define('PLUGIN_DIR', plugin_dir_path(__FILE__));
defined('TEXT_DOMAIN') ? '' : define('TEXT_DOMAIN', 'woocommerce-rest-api');
defined('PLUGIN_URL') ? '' : define('PLUGIN_URL', plugin_dir_url(__FILE__));
defined('API_URL') ? '' : define('API_URL', site_url().'/wp-json/wc/v3/');
/**
 * Create Product List page on plugin activation
 *
 * @return void
 */

function activation_plugin()
{   
    if(!is_plugin_active('woocommerce/woocommerce.php')) {
    ?>
    <div class="notice notice-error is-dismissible">
        <?php wp_die('WooCommerce is not active. Please activate WooCommerce to use the <strong>Gyata Woocommerce</strong> Plugin.'); ?>
    </div>
    <?php
    }
}


register_activation_hook(__FILE__, 'activation_plugin');

// Register the endpoint
add_action('rest_api_init', function () {
    
    /* dynamic endpoint and id set for call woocommerce rest api*/
    register_rest_route('wp/v3', '/(?P<endpoint>[a-zA-Z0-9-]+)/?(?P<id>\d+)?', array(
        'methods' => 'POST',
        'callback' => 'endpoint_callback_function',
        'permission_callback' => 'endpoint_permissions_check', // Allow public access for simplicity
    ));

});

function endpoint_permissions_check(WP_REST_Request $request) {
    $provided_secret_key = $request->get_param('consumer_secret');
    $provided_consumer_key = $request->get_param('consumer_key');
    

    return valid_check_key_permission($provided_secret_key, $provided_consumer_key);
}

function valid_check_key_permission($provided_secret_key, $provided_consumer_key) {
    $stored_secret_key = get_option(sanitize_key('consumer_secret'));
    $stored_consumer_key = get_option(sanitize_key('consumer_key'));

    if (empty($provided_consumer_key) || empty($provided_secret_key)) {
        return new WP_Error('rest_missing_credentials', 'Missing  API credentials', array('status' => 401));
    }

    if ($provided_consumer_key !== $stored_consumer_key || $provided_secret_key !== $stored_secret_key) {
        return new WP_Error('rest_invalid_credentials', 'Invalid API Key credentials.', array('status' => 403));
    }

    if($provided_secret_key === $stored_secret_key && $provided_consumer_key === $stored_consumer_key) {
        return true;
    } else {
        return false;
    }
}

function endpoint_callback_function($request) {
    // Get endpoint and ID from the request
    $endpoint = $request->get_param('endpoint');
    $id = $request->get_param('id');

    // Get consumer key and secret from the request parameters
    $consumer_key = $request->get_param('consumer_key');
    $consumer_secret = $request->get_param('consumer_secret');
    
    // Get the stored consumer key and secret from options
    $valid_consumer_key = get_option('consumer_key');
    $valid_consumer_secret = get_option('consumer_secret');

    // WooCommerce API endpoint URL
    $api_url = rtrim(API_URL, '/') . '/' . $endpoint;

    // Add ID if provided
    if (!empty($id)) {
        $api_url .= '/' . $id;
    }

    // Add consumer_key and consumer_secret as query parameters
    $api_url = add_query_arg(array(
        'consumer_key' => $valid_consumer_key,
        'consumer_secret' => $valid_consumer_secret
        
    ), $api_url);

    // Prepare request arguments
    $args = array(
        'headers' => array(
            'api-type'   => 1,
            'store-url'  => site_url()
        ),
    );

    // Get WooCommerce API response
    $response = wp_remote_get($api_url, $args);

    // Check for errors
    if (is_wp_error($response)) {
        return new WP_REST_Response(array('error' => $response->get_error_message()), 500);
    }

    // Get the response body
    $body = wp_remote_retrieve_body($response);
    $decoded_body = json_decode($body, true);

    // Check for API errors
    if (isset($decoded_body['code']) && isset($decoded_body['message'])) {
        return new WP_REST_Response(array('error' => $decoded_body['message']), wp_remote_retrieve_response_code($response));
    }

    // Return the API response
    return new WP_REST_Response($decoded_body, 200);
}


//Show Notices when WooCommerce is not activate.

function check_woocommerce_activation()
{
    if (!is_plugin_active('woocommerce/woocommerce.php')) {
    ?>
        <div class="notice notice-error is-dismissible">
            <p><?php esc_html_e('WooCommerce is not active. Please activate WooCommerce to use the <strong>Woocommerce</strong> Plugin.', 'woocommerce-rest-api'); ?></p>
        </div>
    <?php
    }
}

//Automatic deactivate plugin when WooCommerce is not active.

function deactivate_on_activation_check()
{

}

add_action('admin_notices', 'check_woocommerce_activation');
add_action('admin_init', 'deactivate_on_activation_check');

本文标签: Get specific values in Woocommerce Rest API