我想做的是每次创建产品时,无论是在后端还是前端,或者通过任何其他方法,创建的产品都会自动设置为类型“外部”,而不是默认的简单产品。
我看到这个答案代码允许更改现有产品的产品类型。我对一切都很陌生,并试图了解如何实现它以添加到我的functions.php 文件中。我想我可以用“外部”替换“变量”类型,以使其适合我。
我如何将该代码实现到 PHP 函数中,将任何创建的产品更改为外部产品类型?
也许将 答案代码 与下面的代码结合起来:
function woo_set_type_function(){
$product_id = 18; //your product ID
wp_remove_object_terms( $product_id, 'simple', 'product_type' );
wp_set_object_terms( $product_id, 'external', 'product_type', true );
}
add_action('init', 'woo_set_type_function');
我没有经验,我不想通过尝试自己组合来破坏函数文件中的任何内容。
外部产品的类名是
WC_Product_External
,所以我们不需要使用WC_Product_Factory
来获取外部产品的产品类名。
您可以使用以下挂钩函数将任何非外部产品更改为外部产品:
add_action('woocommerce_init', 'change_product_to_external_type');
function change_product_to_external_type(){
$product_id = 18; // Define your product ID
$product = wc_get_product($product_id); // Get the product object
// Check that the current product is not external
if ( ! $product->is_type('external') ) {
// Get an external product instance of the product
$product = new WC_Product_External( $product_id );
$product->save(); // Save product to database and sync caches
}
}
应该有效
对于定义的产品 IDS 数组,请使用以下内容:
add_action('woocommerce_init', 'change_product_to_external_type');
function change_product_to_external_type(){
$product_ids = array( 18, 19, 25); // Define your product IDs in the array
// Loop through the array of product IDs
foreach ( $product_ids as $product_id ) {
$product = wc_get_product($product_id); // Get the product object
// Check that the current product is not external
if ( ! $product->is_type('external') ) {
// Get an external product instance of the product
$product = new WC_Product_External( $product_id );
$product->save(); // Save product to database and sync caches
}
}
}
代码位于子主题的functions.php 文件中(或插件中)。应该可以。