افزودن محصول در ووکامرس
<?php
//add product dynamically
add_action('init',function(){
if(isset($_POST['pname-wordpress'])) {
//add post
$post_id = wp_insert_post( array(
'post_title' => trim($_POST['pname-wordpress']),
'post_content' => '',
'post_status' => 'draft',
'post_type' => "product",
));
//add category
wp_set_object_terms( $post_id, (int)$_POST['cat'], 'product_cat' );
//add post metaphone
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, '_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', '' );
//add attribute
$product_attributes = array();
$opt_name = 'attr-cat-'.$_POST['cat'];
if(get_option($opt_name)){
$gpt = get_option($opt_name);
$i =0;
foreach(get_list_attribute_slug() as $attr) {
if(in_array($attr['id'],$gpt)) {
$product_attributes[sanitize_title('pa_'.$attr['name'])] = array (
'name' => wc_clean('pa_'.$attr['name']), // set attribute name
'value' => '0', // set attribute value
'position' => $i,
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 1
);
$i++;
}
}
}
//echo "<pre>";
//print_r($product_attributes);
update_post_meta( $post_id, '_product_attributes', $product_attributes );
wp_redirect(admin_url().'post.php?post='.$post_id.'&action=edit');
exit;
}
});