【问题标题】:Assign value from a custom field to the price for a user role in Woocommerce将自定义字段的值分配给 Woocommerce 中用户角色的价格
【发布时间】:2022-11-16 09:10:32
【问题描述】:

我已经创建了一个名为“批发”的用户角色。

我习惯于跟随 sn-p 在每个产品上创建一个自定义字段,允许我在其中输入一些值:

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 thread 但它对我不起作用。

【问题讨论】:

    标签: php wordpress woocommerce e-commerce


    【解决方案1】:

    我一直在使用这种技术在前端更新价格,我只是为您稍微修改了一下,希望它对您有用。

    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;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-07
      • 2016-12-04
      • 2020-11-19
      • 2012-09-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多