skip to Main Content

How do I write Title + Variation in products _SKU (for a simple product only Title)? This is necessary to update existing products in the store (more than 8000) via WP All Import and add new ones. Now updates only simple products..
I’m trying this, but still not working…

function wpse_177056_init_shortcode() {
$args = array(
    'post_type' => 'product'
);
$products = new WP_Query( $args );
if ( $products->have_posts() ):
    while ( $products->have_posts() ):
        $products->the_post();
        update_post_meta( $post->ID, '_sku', 'test' );
    endwhile; 
endif;
}
add_action( 'init', 'wpse_177056_init_shortcode' );

2

Answers


  1. Chosen as BEST ANSWER

    Set more time limit if you have a lot of products...

    add_filter( 'init', 'sku_from_title_and_variation', 10, 1);
    function sku_from_title_and_variation(){
        set_time_limit(300);
    $query = array(
        'numberposts' => -1,
        'post_status' => 'published',
        );
        $products = wc_get_products( $query );
    
        foreach ($products as $product) {
    
          if( $product->is_type('variable') ){
    
            $product_id = $product->get_id();
    
            $product_title = $product->get_title();
    
            update_post_meta( $product_id, '_sku', $product_title );
    
            wc_delete_product_transients( $product_id );
    
            foreach( $product->get_available_variations() as $variation_values ){
    
              $variation_id = $variation_values['variation_id']; // variation id
              $variation_attr = $variation_values['attributes'];
              $variation_attr = $variation_attr['attribute_pa_variant'];
              $variation_attr = get_term_by('slug', $variation_attr , 'pa_variant')->name;
    
              update_post_meta( $variation_id, '_sku', $product_title.$variation_attr );
    
              wc_delete_product_transients( $variation_id );
            }
            wc_delete_product_transients( $product->get_id() );
    
          } else {
    
              update_post_meta( $product->get_id(), '_sku', $product->get_title());
    
              wc_delete_product_transients( $product->get_id() );
          }
        }
    
    }
    

  2. You can use set_sku function to update SKU’s

    foreach( $products as $product){
    
        // Set Product name as SKU
        $variable = esc_html( strtolower ( $product->name ) );
        $product->set_sku( $variable );
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search