PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 27, 2022

[FIXED] Set product shipping class based on metadata in WooCommerce

 January 27, 2022     metadata, php, product, woocommerce, wordpress     No comments   

Issue

I'm trying to write a specific function that allow to change automatically the product shipping class when a WooCommerce custom field is set with a specific value.

Please find below the screenshot about the custom fields

enter image description here


This is the code I had thought of but obviously it doesn't work.

function woo_on_product_save( $post_id ) {
    $title = $product->get_meta( 'meta_easyfatt_libero_1' );
    if ( $title = 'Trenta' ) {
        $shipping_class_id = 1182;
    }

    $product = wc_get_product( $post_id );
    $product->set_shipping_class_id( $shipping_class_id );
    $product->save();
}
add_action( 'woocommerce_process_product_meta', 'woo_on_product_save', 100 );

Any suggestions would be greatly appreciated!


Solution

You have some minor mistakes

  • You use $product->get_meta(.. while $product is not defined
  • The comparison operator in an if statement is ==, not =
  • Use woocommerce_admin_process_product_object to save instead of the outdated woocommerce_process_product_meta hook

So you get:

// Save
function action_woocommerce_admin_process_product_object( $product ) {
    // Get meta
    $title = $product->get_meta( 'meta_easyfatt_libero_1' );
    
    if ( $title == 'Trenta' ) {
        // The targeted shipping class ID to be set for the product
        $shipping_class_id = 1182;

        // Set the shipping class ID 
        $product->set_shipping_class_id( $shipping_class_id );
    }
}
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object', 10, 1 ); 


Answered By - 7uc1f3r
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing