Mosi
Mosi

Reputation: 355

WordPress : how add new post meta before saving product woocommerce

i have a api from another wocommerce website and take some information with my product sku how can i add this information to post meta after created new product ? i wanna when i create a product , the information take with api and product sku and save to post meta.

i found this hook but i think this not working

<?PHP
function my_product_att( $sku ) {
   // my api codes and take information and use      
   add_post_meta('product_id','key','value');
   // i haven't problem here i just need Appropriate hook 
}
add_action( 'save_post', 'my_product_att' ); // this hook not work for woocommerce

Upvotes: 2

Views: 4787

Answers (3)

vivek manavadariya
vivek manavadariya

Reputation: 230

add_action( 'save_post', 'prowp_save_meta_boxdddd' );
function prowp_save_meta_boxdddd( $post_id ) {
    global $wpdb;
    $table_prefix = $wpdb->prefix;
    $tablename = $table_prefix.'postmeta';
    $wpdb->query($wpdb->prepare('UPDATE '.$tablename.' SET meta_value="test" WHERE post_id='.$post_id));
}

Upvotes: 0

Milap
Milap

Reputation: 7221

Woocommerce Products are wordPress posts. You can use wordpress hooks like save_post & $post_id as its argument. You are passing $sku which is wrong.

add_action( 'save_post', 'wpse_110037_new_posts' );
function wpse_110037_new_posts($post_id){
    $post_type = get_post_type($post_id);
    if($post_type == 'products') {
        add_post_meta($post_id,'key','value');
    }
}

Upvotes: 3

vidhi
vidhi

Reputation: 104

Try below code. Note that in code $unique is true or false based on if meta value should be unique or not.

add_action('transition_post_status', 'product_created_function', 10, 3);
function product_created_function($newstatus, $oldstatus, $post) {
    if($oldstatus != 'publish' && $newstatus == 'publish' && !empty($post->ID) && in_array( $post->post_type, array( 'product') ) ) {
         add_post_meta( $post->ID, $key, $value,$unique );
    }    
 }

Upvotes: 1

Related Questions