0

I have a user role called "Wholesale" already created.

I have used to following snippet to create a custom field on every product that allows me to input some value in it:

function snippet_add_custom_pricing() {
    $args = array(
     'label' => __( 'Wholesale', 'woocommerce' ),
     'placeholder' => __( 'Price for wholesale', 'woocommerce' ),
     'id' => 'snippet_wholesale',
     'desc_tip' => true,
     'description' => __( 'Price for Wholesale.', 'woocommerce' ),
     );
    woocommerce_wp_text_input( $args );
   }
    
add_action( 'woocommerce_product_options_pricing', 'snippet_add_custom_pricing' );
  
    function snippet_save_custom_meta( $post_id ) {
     // Value of the price
     $pricing = isset( $_POST[ 'snippet_wholesale' ] ) ? sanitize_text_field( $_POST[ 'snippet_wholesale' ]     ) : '';
    
      // Name of the product
      $product = wc_get_product( $post_id );
    
      // Saves Metafield
      $product->update_meta_data( 'snippet_wholesale', $pricing );
      $product->save();

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

This is working, now I just want to show the values introduced here to all Wholesale users, so that when they login they get the price that is inserted on this field and not the regular price. Is this possible?

I've tried this thread but it did not work for me.

Sophie
  • 1

1 Answers1

0

I have been using this technique to update prices on the front end, I just modified it a little bit for you, and I hope it will work for you.

add_filter( 'woocommerce_get_price_html', 'get_wholesaler_price', 100, 2 );
function get_wholesaler_price( $price, $product ) {
    if(!is_user_logged_in()) {
        return $price;
    }else{
        $user = wp_get_current_user();
        $user_roles = $user->roles;
        if(in_array('wholesaler', $user_roles)){
            $price = get_post_meta($product->id,'snippet_wholesale', true);
            //or 
            //$price = $product->get_meta_data('snippet_wholesale');
           
            return $price;
        }else{
            return $price;
        }
    }
}
Ishtiaq Ahmed
  • 126
  • 1
  • 11