What WooCommerce API should I use on the server?

前端 未结 2 1417
情书的邮戳
情书的邮戳 2021-01-03 05:38

I am writing a script to bulk-change product properties such as price, weight and dimension. I need to run the script directly on the server where WordPress (4.7.2) and WooC

2条回答
  •  情书的邮戳
    2021-01-03 06:41

    It turns out that you can use the REST API on the server without neither authenticating nor performing an HTTP request: you just need to build a WP_REST_Request object and pass it directly to the API.

    Example: Show a Product

    Here's an example PHP script which will print information on a product based on its ID, using the REST API. The script should be placed in the WordPress folder and executed in a browser; the product ID is given as a query parameter, ex: http://www.yourwebsite.com/script.php?id=123.

    get_item( $request );
    
        /* Print to screen the response from the API.
        The product information is in $response->data  */
        print_r( $response );
    
        /* Also print to screen the product object as seen by WooCommerce */
        print_r( wc_get_product( $product_id ) );
    
    }
    

    Example: Create a Product

    The next script will create a new product. The product's deatails should be entered directly in the script, in the set_body_params() function. For a list of the allowed fields, just print any product's data using the previous script.

    /* Load WordPress */
    require('wp-load.php');
    
    /* Create an API controller */
    $api = new WC_REST_Products_Controller();
    
    /* Build the request to create a new product */
    $request = new WP_REST_Request ('POST', '', '');
    $request->set_body_params( array (
        'name' => 'New Product',
        'slug' => 'new-product',
        'type' => 'simple',
        'status' => 'publish',
        'regular_price' => 60,
        'sale_price' => 40,
    ));
    
    /* Execute the request */
    $response = $api->create_item( $request );
    
    /* Print to screen the response from the API */
    print_r( $response );
    
    /* Also print to screen the product object as seen by WooCommerce */
    print_r( wc_get_product( $response->data['id'] ) );
    

    Some basic security measures

    It's not a good idea to leave executable PHP scripts on your website. I would rather incorporate them in a plugin, and make them accessible only to authorized users. To achieve that, it might be useful to prepend the following code to the scripts:

    /* Load WordPress. Replace the /cms part in the path if
    WordPress is installed in a folder of its own. */
    try {
        require($_SERVER['DOCUMENT_ROOT'] . '/cms/wp-load.php');
    } catch (Exception $e) {
        require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
    }
    
    /* Restrict usage of this script to admins */
    if ( ! current_user_can('administrator') ) {
      die;
    }
    

提交回复
热议问题