Accessing WC_Product protected data in Woocommerce 3

前端 未结 1 660
悲&欢浪女
悲&欢浪女 2021-02-10 13:41

I have this answer for reference: Woocommerce Get Product Values by ID … It is about the function wc_get_product() that returns protected data.

Where are th

1条回答
  •  無奈伤痛
    2021-02-10 14:29

    The wc_get_product( $product_id) function gives the WC_Product instance object (from a product ID) where data can be accessed with all available WC_Product methods and WC_Product sub-classes depending on the product type:

    // Get the instance of the WC_Product Object
    $product = wc_get_product( $product_id);
    
    // Using `WC_Product` methods examples to get specific related data values:
    
    $product_type  = $product->get_type(); // product Type
    $product_id    = $product->get_id(); // product ID
    $product_name  = $product->get_name(); // product name
    $product_sku   = $product->get_sku(); // product SKU
    $product_price = $product->get_price(); // product price
    
    // And so on…
    
    // The raw display of the object protected data (Just for testing)
    echo '
    '; print_r( $product ); echo '
    ';

    You can unprotect the data using the WC_Data method get_data() that will give you an accessible array of the data:

    // Get the instance of the WC_Product Object
    $product = wc_get_product( $product_id);
    
    // Get the accessible array of product properties:
    $data = $product->get_data();
    
    // get specific related data values:
    
    $product_id    = $data['id']; // product ID
    $product_name  = $data['name']; // product name
    $product_sku   = $data['sku']; // product SKU
    $product_price = $data['price']; // product price
    
    // And so on…
    
    // The raw display of the unprotected data array (Just for testing)
    echo '
    '; print_r( $data ); echo '
    ';

    For specific custom meta data you can use the WC_Data method get_meta(). So if the custom meta key is for example _custom_height you will use:

    $custom_product_height = $product->get_meta( '_custom_height' );
    

    Official Woocommerce API Documentation:

    • WC_Product list of methods
    • WC_Product_External list of methods
    • WC_Product_Grouped list of methods
    • WC_Product_Simple list of methods
    • WC_Product_Variable list of methods
    • WC_Product_Variation list of methods
    • WC_Data list of methods

    0 讨论(0)
提交回复
热议问题