2015-02-05 66 views
2

我嘗試獲取分組產品的類型,但如果我使用WC_Product_Factory,woocommerce將返回空或始終「簡單」。wordpress返回woocommerce總是很簡單,因爲產品類型

當我使用:

$the_product = new WC_Product(2886); 
echo $the_product->product_type; 

返回空。

當我使用WC_Product_Factory:

總是返回 「簡單」

我嘗試使用:

$the_product = wc_get_product(2886); 
echo $the_product->product_type; 

但這返回一個錯誤「調用一個成員函數get_product( )在非對象中...「

我的代碼位於:

add_action('plugins_loaded', function(){ 
    $the_product = new WC_Product(2886); 
    echo $the_product->product_type; 

    $the_product = new WC_Product(2886); 
    $the_product_factory = new WC_Product_Factory(); 
    $the_product = $the_product_factory->get_product($the_product); 
    echo $the_product->product_type; 

    $the_product = wc_get_product(2886); 
    echo $the_product->product_type; 

    die(); 
}); 

恩,謝謝你的幫忙!

回答

1

我找到了解決辦法或者我的錯誤,改變plugins_loaded來初始化:

add_action('init', function(){ 
    $the_product = new WC_Product(2886); 
    echo $the_product->product_type; 

    $the_product = new WC_Product(2886); 
    $the_product_factory = new WC_Product_Factory(); 
    $the_product = $the_product_factory->get_product($the_product); 
    echo $the_product->product_type; 

    $the_product = wc_get_product(2886); 
    echo $the_product->product_type; 
    die(); 
}); 

這項工作!

此網址https://wordpress.stackexchange.com/questions/120055/woocommerce-create-new-product-and-add-to-cart-on-form-submit給了我這個想法。

快樂編碼! :)

1

您可以使用此代碼來獲取自定義產品類型:

$terms = get_the_terms($product_id, 'product_type'); 
$product_type = !empty($terms) ? sanitize_title(current($terms)->name) : 'simple'; 
+1

這救了我的天.. – mthama 2017-02-16 00:19:09

相關問題