Create a Woocommerce product when post is created

亡梦爱人 提交于 2019-12-08 07:33:49

问题


I am using Woocommerce on my WordPress site. and I am Selling Various items on my site.

What I want is that every time I create a small post about a particular item.it also creates a Woocommerce product page with the one item available to be sold.

For example: I create a post about custom-made jewelry and I write a small post about it, and the customer can look at the post and buy it from the Woocommerce product section.
Once the product is out of stock the post disappears"Hidden" until I have them in stock.

How this can be done? Any ideas?


回答1:


Add this to your function file and replace empty strings with variable where necessary. This should solve your problem.

add_action( 'save_post', 'auto_create_product_from_post', 100, 2 ); 
function auto_create_product_from_post($id, $post){
$post_id = wp_insert_post( array(
    //'post_title' => 'Adams Product',
    'post_title' => $post.post_title,
    'post_content' => $post.post_title,
    'post_status' => 'publish',
    'post_type' => "product",
) );
    wp_set_object_terms( $post_id, 'simple', 'product_type' );
    update_post_meta( $post_id, '_visibility', 'visible' );
    update_post_meta( $post_id, '_stock_status', 'instock');
    update_post_meta( $post_id, 'total_sales', '0' );
    update_post_meta( $post_id, '_downloadable', 'no' );
    update_post_meta( $post_id, '_virtual', 'yes' );
    update_post_meta( $post_id, '_regular_price', '' );
    update_post_meta( $post_id, '_sale_price', '' );
    update_post_meta( $post_id, '_purchase_note', '' );
    update_post_meta( $post_id, '_featured', 'no' );
    update_post_meta( $post_id, '_weight', '' );
    update_post_meta( $post_id, '_length', '' );
    update_post_meta( $post_id, '_width', '' );
    update_post_meta( $post_id, '_height', '' );
    update_post_meta( $post_id, '_sku', '' );
    update_post_meta( $post_id, '_product_attributes', array() );
    update_post_meta( $post_id, '_sale_price_dates_from', '' );
    update_post_meta( $post_id, '_sale_price_dates_to', '' );
    update_post_meta( $post_id, '_price', '' );
    update_post_meta( $post_id, '_sold_individually', '' );
    update_post_meta( $post_id, '_manage_stock', 'no' );
    update_post_meta( $post_id, '_backorders', 'no' );
    update_post_meta( $post_id, '_stock', '' );
}


来源:https://stackoverflow.com/questions/49766263/create-a-woocommerce-product-when-post-is-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!