doujiu9307 2018-06-12 18:51
浏览 137
已采纳

在空的时候添加产品尺寸 - 添加/编辑产品 - Woocommerce

Shipping rates are calculated using product weight and dimension on my Woocommerce website. However, my inventory system only uses product weight for shipping rates. Because of this, new products synchronized from the inventory system to the website generally don't have dimensions.

After a few tests, I found that adding a length, width and height of .001 to products on the site generates the most accurate shipping rates.

I need to write a function that sets product dimensions to .001 if they're empty at the point of creation.

Here is what I've attempted:

function add_default_dimension_if_empty( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( $meta_key == '_edit_lock' ) {
        if ( get_post_type( $post_id ) == 'product' ) {
            //get product
            $product = wc_get_product( $post_id );
            $newDim = .001;
            if($product->has_dimensions()){
                if(empty( $product->get_length() )){
                    update_post_meta($post_id, '_length', $newDim);
                }
                if(empty( $product->get_width() )){
                    update_post_meta($post_id, '_width', $newDim);
                }
                if(empty( $product->get_height() )){
                    update_post_meta($post_id, '_height', $newDim);
                }
            }
        }
    }
}
add_action( 'added_post_meta', 'add_default_dimension_if_empty', 10, 4 );
add_action( 'updated_post_meta', 'add_default_dimension_if_empty', 10, 4 );

I used the structure from this article, but it doesn't seem to work. Any thoughts?

  • 写回答

1条回答 默认 最新

  • doulandai0641 2018-06-13 06:01
    关注

    Your code is fine just need to change one condition which check the dimension is exist or not. Replace if($product->has_dimensions()) line with following

        $dimensions = $product->get_dimensions();
        if(! empty( $dimensions ))
    

    This will work for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?