WooCommerce

WooCommerce Product API(2021)

WooCommerce Product API是WooCommerce产品的类,熟悉这个类就能自由操作产品,本文介绍的函数主要来自abstract-wc-product.php,并包含一些variation product的内容。

WooCommerce Product API代码示例

代码如下,从根据ID初始化一个产品开始,有了产品实例,就可以调用产品的各种方法获取信息,或改变产品的属性。

源代码:abstract-wc-product.php

// Create a variation product instance by wc_get_product which creates product instance through factory
// You don't need to care about what type the product is
$product = wc_get_product(11);

// Getters
$product->get_title();
$product->get_permalink();
$product->get_children();
$product->get_formatted_name();
$product->get_min_purchase_quantity();
$product->get_max_purchase_quantity();
$product->single_add_to_cart_text();
$product->add_to_cart_url();
$product->single_add_to_cart_text();
$product->add_to_cart_text();
$product->add_to_cart_description();

// Image html
$product->get_image();
$product->get_shipping_class();

// Returns a single product attribute as a string - "Gray, Pink"
$product->get_attribute('color');
$product->get_rating_count();
$product->get_rating_count();
$product->get_price_suffix();

/**
 * Returns the availability of the product
 * array (
      'availability' => '100 in stock',
      'class' => 'in-stock',
    )
 */
$product->get_availability();

// Get the type of the product -- 'variable'
$product->get_type();

// Get the id of the product
$product->get_id();

// Get product name -  'Baby clothes flower print 100% cotton wholesale'
$product->get_name();

// Get product slug - "baby-clothes-flower-print-100-cotton-wholesale"
$product->get_slug();

// Get product created date - return a WC_DateTime object
$product->get_date_created();

// Get product modified date - return a WC_DateTime object
$product->get_date_modified();

// Get product status - "publish"
$product->get_status();

// If the product is featured. - false
$product->get_featured();

/**
 * Get catalog visibility
 * Return values are:
 * "Shop and search results" - "visible"
 * "Shop only" - "catalog"
 * "Search results only" - "search"
 * "Hidden" - "hidden"
 */
$product->get_catalog_visibility();

// Get product description
$product->get_description();

// Get product short description
$product->get_short_description();

// Get SKU (Stock-keeping unit) - product unique ID.
$product->get_sku();

// Returns the product's active/regular/sale price (for simple product)
$product->get_price();
$product->get_regular_price();
$product->get_sale_price();

// Get date on sale from and to, click the schedule besides "Sale price" to enter the dates. For variations, use the variation id
// return a WC_DateTime object
$product->get_date_on_sale_from();
$product->get_date_on_sale_to();

// Get number total of sales
$product->get_total_sales();

// Returns the tax status - taxable,taxable,none
$product->get_tax_status();

// Returns the tax class. - reduced-rate,zero-rate and '' for "Standard"
$product->get_tax_class();

// Return if product manage stock
// This is true for variable product only if "Enable stock management at product level" is enabled
// For variable product, use variation id to check if the child is managing stock itself
$product->get_manage_stock();

// Returns number of items available for sale
$product->get_stock_quantity();

// Return the stock status - "instock"
$product->get_stock_status();

// Get backorders - yes,no,notify
$product->get_backorders();

// Get low stock amount
$product->get_low_stock_amount();

// Return if should be sold individually
$product->get_sold_individually();

// Get weight/length/width/height
$product->get_weight();
$product->get_length();
$product->get_width();
$product->get_height();

// Get upsell IDs
//  array (0 => 33,)
$product->get_upsell_ids();

// Get the parent ID of the variation
wc_get_product(35)->get_parent_id();

// Return if reviews is allowed.
$product->get_reviews_allowed();

// Get purchase note which is under Advanced tab
// https://jilt.com/blog/how-to-show-woocommerce-product-information-after-purchase/#using-woocommerce-purchase-notes
$product->get_purchase_note();

/**
 * Get category ids. 
 * array (
      0 => 16,
      1 => 15,
    )
 */
$product->get_category_ids();
$product->get_tag_ids();

// Returns the gallery attachment ids
$product->get_gallery_image_ids();

// Get main image ID
$product->get_image_id();

// Get a array of rating counts
$product->get_rating_counts();

// Get average rating.
$product->get_average_rating();

// Get review count
$product->get_review_count();

/**
 * Return a products child ids
 *  array (
      0 => 35,
      1 => 32,
    )
 */
$product->get_children();

// Return a products child ids - visible only.
$product->get_visible_children();

/**
 * Get an array of all sale and regular prices from all variations
 * array (
      'price' => 
          array (
            32 => '10.00',
            35 => '12.00',
          ),
          'regular_price' => 
          array (
            32 => '10.00',
            35 => '12.00',
          ),
          'sale_price' => 
          array (
            32 => '10.00',
            35 => '12.00',
          ),
    )
 */


$product->get_variation_prices();

// Get the min or max variation regular price. prarms:min or max
$product->get_variation_regular_price('min');

// Get the min or max variation sale price.
$product->get_variation_sale_price('max');

/**
 * Returns the price in html format.
 * '$10.00 – $12.00'
 * <span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">$</span>10.00</bdi></span>
 */
$product->get_price_html();

// Get the min or max variation (active) price.
$product->get_variation_price('min');

// Get the add to cart button text description - used in aria tags. --Select options for "[pproduct name]"
$product->add_to_cart_description();

// Get the add to cart button text. -- select options
$product->add_to_cart_text();

// Get the add to url used mainly in loops.  -- the same as the permalnk???
$product->add_to_cart_url();

// Returns whether or not the product can be backordered(调货)
$product->backorders_allowed();

// Returns whether or not the product needs to notify the customer on backorder.
$product->backorders_require_notification();

// Does a child have dimensions set?
$product->child_has_dimensions();

// Get the suffix to display after prices > 0
// Enable tax by settings->general->Enable tax rates and calculations, then under tax tab enter "Price display suffix"
$product->get_price_suffix();

/**
 * If set, get the default attributes for a variable product.
 */
$product->get_variation_default_attribute('pa_color');

// Get an array of available variations for the current product.
$product->get_available_variations();

// Returns an array of data for a variation. Used in the add to cart form.
$product->get_available_variation(32);


/**
 * Return an array of attributes used for variations, as well as their possible values.
 * array (
      'pa_color' => 
      array (
        0 => 'pink',
        1 => 'gray',
      ),
      'pa_size-age' => 
      array (
        0 => '0-3-months',
        1 => '12-24-months',
        2 => '3-6-months',
        3 => '6-9-months',
        4 => '9-12-months',
      ),
    )
*/
$product->get_variation_attributes();


/**
 * Variations of a variable product are also products/posts which have their own post_ids
 * Variable products themselves cannot be downloadable or virtual, but their children can.
 * 
 */
$children = $product->get_children();
foreach($children as $id){
    $child        = wc_get_product($id);
    $type         = $child->get_type();
    $downloadable = $child->get_downloadable();
    $vitural      = $child->get_virtual();
    $product_name = $child->get_name();
}

/**
* array (
  'pa_color' => 'gray',
  'pa_size-age' => '0-3-months',
)
*/
$product->get_default_attributes();

/**
 * Create or update depending on if we are working on an existing product
 * Setters
 */
function sola_modify_product( $post_id = ''){

    if( $post_id ){
        $myproduct = new WC_Product(absint($post_id));
    } else{
        $myproduct = new WC_Product();
    }
    $myproduct->set_name('My very own product');
    $myproduct->set_slug('my-very-own-product');
    $myproduct->set_status('publish');
    $myproduct->set_featured(true);
    $myproduct->set_catalog_visibility('visible');
    $myproduct->set_description('whatever the description is');
    $myproduct->set_short_description('short desc');
    $myproduct->set_regular_price(100);
    $myproduct->set_manage_stock(true);
    $myproduct->set_stock_quantity(100);
    $myproduct->set_review_count(100);
    $myproduct->set_image_id(15);
    $myproduct->set_gallery_image_ids(array(15,16));

    $result = $myproduct->save();

    if( $result ){
        if( $post_id ){
            echo "Product [$post_id] was modified";
        } else {
            echo "Product [$result] was created";
        }
    }
}


/**
 * Delete a product by code
 */
function sola_delete_product(){
    $myproduct = wc_get_product(40);
    $myproduct->delete();
}

// Check functions
$product->exists();
$product->is_type('variation');
$product->is_downloadable();
$product->is_virtual();
$product->is_featured();
$product->is_sold_individually();
$product->is_visible();
$product->is_purchasable();
$product->is_on_sale();
$product->has_dimensions();
$product->has_weight();
$product->is_in_stock();
$product->needs_shipping();
$product->is_taxable();
$product->is_shipping_taxable();
$product->managing_stock();
$product->backorders_allowed();
$product->backorders_require_notification();
$product->is_on_backorder();

// Check managing_stock first before checking enough stock
$product->has_enough_stock(20);

$product->has_attributes();
$product->has_child();
$product->has_file();


// True if any child is in stock
$product->child_is_in_stock();

// True if all children are allowed backorder
$product->child_is_on_backorder();

// True if any child does
$product->child_has_weight();
$product->child_has_dimensions();