Skip to content

Instantly share code, notes, and snippets.

@aoktox
Created August 17, 2016 05:00
Show Gist options
  • Save aoktox/6140084922f2770f95a5816cf932d4e5 to your computer and use it in GitHub Desktop.
Save aoktox/6140084922f2770f95a5816cf932d4e5 to your computer and use it in GitHub Desktop.
Insert and set attributes product woocommerce
<?php
/**
* Plugin Name: Insert Products
* Plugin URI:
* Description:
* Version: 1.04
* Author: Agus Prasetiyo
* Author URI:
* License: GPL2
* Created On:
* Updated On:
*/
//call addaprdct function when plugin is activated by admin:
register_activation_hook( __FILE__, 'addaprdct' );
function addaprdct(){
$post_id = wp_insert_post( array(
'post_title' => "Product baru gan 2",
'post_content' => "product post content goes here...",
'post_status' => "publish",
'post_excerpt' => "product excerpt content...",
'post_name' => "test_prod_gan2", //name/slug
'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, '_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', '' );
// After inserting post
$my_product_attributes = array('hdd_size' => '500', 'ram_size' => '4');
wcproduct_set_attributes($post_id, $my_product_attributes);
}
function wcproduct_set_attributes($post_id, $attributes) {
$i = 0;
// Loop through the attributes array
foreach ($attributes as $name => $value) {
$product_attributes[$i] = array (
'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name
'value' => $value, // set attribute value
'position' => 1,
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0
);
$i++;
}
// Now update the post with its new attributes
update_post_meta($post_id, '_product_attributes', $product_attributes);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment