skip to Main Content

I need a little help if it will be possible on product pricing,

I need when a Product is being successfully added in the database i want its “Regular Price” to be automatically added by particular amount, this should apply in all products added and it is a flat amount to all products.

Example: If a regular product of T-shirt is $25 i need that $25 to be added by $5 automatically when the product is added to the database so the end user (Customer) can see the final price as $30.

enter image description here

function set_default_price( $post_id, $post ) {

    if ( isset( $_POST['_regular_price'] ) && trim( $_POST['_regular_price'] ) == '' ) {
        update_post_meta( $post_id, '_regular_price', '5' );
    }


}
add_action( 'woocommerce_process_product_meta', 'set_default_price' );

I have found this code but it does not do the work & i’m not good with PHP

Any idea on what should i do?

2

Answers


  1. According to provided code, to implement required functionality of changing woocommerce product regular price, the following code can be checked:

    function set_default_price( $post_id ) {
        if ( isset( $_POST['_regular_price'] ) && !empty( trim( $_POST['_regular_price'] ) ) ) {
            update_post_meta( $post_id, '_regular_price', trim( $_POST['_regular_price'] ) + 5 );
        }
    }
    add_action( 'woocommerce_process_product_meta', 'set_default_price' );
    
    Login or Signup to reply.
  2. Since WooCommerce 3, you can use CRUD methods and hooks as follows, to add automatically on product creation, a defined flat amount to the regular price:

    add_action( 'woocommerce_admin_process_product_object', 'woocommerce_admin_process_product_object_callback' );
    add_action( 'woocommerce_admin_process_variation_object', 'woocommerce_admin_process_product_object_callback' );
    function woocommerce_admin_process_product_object_callback( $product ) {
        if ( $product->get_meta('_flat_amount_added') !== 'yes' && isset($_POST['_regular_price']) ) {
            $flat_amount = 5; // Define the flat amount to be added to the regular price
    
            $regular_price = (float) $product->get_regular_price('edit');
            $product->set_regular_price($regular_price + $flat_amount);
            $product->add_meta_data('_flat_amount_added', 'yes', true);
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and work for all WooCommerce products, including product variations…

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search