Wordpress Woocommerce - use update_post_meta to add product attributes

后端 未结 4 1114
广开言路
广开言路 2020-12-05 15:56

The products in my clients website require certain attributes which I have added via Products -> Attributes in the Wordpress administration. In this import script I\'

4条回答
  •  Happy的楠姐
    2020-12-05 16:36

    Don't know if this is the "correct" way to do this... But I needed a function to add ACF repeater fields with a date value as a attribute on post save, so this was the function I came up with:

    add_action( 'save_post', 'ed_save_post_function', 10, 3 );
    
    function ed_save_post_function( $post_ID, $post, $update ) {
      //print_r($post);
      if($post->post_type == 'product')
        {
         $dates = get_field('course_dates', $post->ID);
         //print_r($dates);
         if($dates)
           {
            $date_arr = array();
            $val = '';
            $i = 0;
            foreach($dates as $d)
                   {
                     if($i > 0)
                       {
                        $val .= ' | '.date('d-m-Y', strtotime($d['date']));   
                       }
                   else{
                        $val .= date('d-m-Y', strtotime($d['date']));
                       } 
                     $i++;  
                   }
                $entry = array(
                               'course-dates' => array(
                                                       'name' => 'Course Dates',
                                                       'value' => $val,
                                                       'position' => '0',
                                                       'is_visible' => 1,
                                                       'is_variation' => 1,
                                                       'is_taxonomy' => 0
                                                      )
                              );
                    update_post_meta($post->ID, '_product_attributes', $entry);
           }
        }
    }
    

    Hope this helps someone.

提交回复
热议问题