【问题标题】:Show a % based on a product price in woocommerce根据 woocommerce 中的产品价格显示百分比
【发布时间】:2018-07-17 23:42:23
【问题描述】:

我想计算 woocommerce 中当前产品价格的百分比 (%)。 对我来说最好的是能够将代码添加到每个产品中,因为不同的产品会有不同的通行费百分比。 所以,如果有一个函数或 Javascript 这将是很棒的..

抱歉,我在任何地方都找不到任何代码。

  • 产品价格:100美元
  • 通行费(2%):$2

“如果您订购此产品,您必须支付 $2 的通行费”

公式:100 * 0,02

谢谢大家!

【问题讨论】:

  • 你问的是如何将两个数相乘?
  • 呵呵,有点。我不是编码员,所以我需要帮助为此设置一个 sn-p

标签: javascript wordpress woocommerce price


【解决方案1】:

一个简单的 Javascript 解决方案不足以解决这个问题。在计算应付总额之前,您需要更新购物车商品价格。否则根本不会向您的客户收费。

我写了一个简单的插件来解决这个问题。这是代码-

<?php

/*
* Plugin Name: Toll on products
* Plugin URI: http://makjoybd.com/projetcs/wordpress/plugins/toll-on-product/
* Description: Allow to have tolls on products
* Author: Mahbub Alam <makjoybd@gmail.com>
* Version: 1.0
* Author URI: http://makjyoybd.com/
*/

class Toll_On_Products{
    public function __construct(  ) {

        //  initialization
        add_action( 'admin_init', array($this, 'woocommerce_installed') );


        //  setup field in the product edit page
        add_action( 'woocommerce_product_options_general_product_data', array($this, 'product_fields') );
        add_action( 'woocommerce_process_product_meta', array($this, 'save_field_input') );

        //  display notification in the product page.
        add_action('woocommerce_after_shop_loop_item_title', array($this, 'notification') );
        add_action('woocommerce_single_product_summary', array($this, 'notification') );
        add_action('woocommerce_cart_item_subtotal', array($this, 'cart_notification'), 20, 3 );

        add_shortcode( 'product-toll-amount', array($this, 'product_toll_amount') );

        // Uncomment it if you want to charge your users    
        // add_action( 'woocommerce_before_calculate_totals', array($this, 'add_toll_price') );
    }

    /**
     * Check if woocommerce is already installed or not
     * If woocommerce is not installed then disable this plugin
     * and show a notice in admin screen.
     */

    public function woocommerce_installed() {
        if ( is_admin() && ( ! class_exists( 'WooCommerce' ) && current_user_can( 'activate_plugins' ) ) ) {
            add_action( 'admin_notices', array($this, "admin_notification") );

            deactivate_plugins( plugin_basename( __FILE__ ) );

            if ( isset( $_GET['activate'] ) ) {
                unset( $_GET['activate'] );
            }
        }
    }

    public function admin_notification(  ) {
        echo '<div class="error"><p>' . sprintf( __('Activation failed: <strong>WooCommerce</strong> must be activated to use the <strong>Toll on products</strong> plugin. %sVisit your plugins page to install and activate.', 'woocommerce' ), '<a href="' . admin_url( 'plugins.php#woocommerce' ) . '">' ) . '</a></p></div>';
    }

    /**
     * add toll amount field in the product general tab
     */

    public function product_fields(  ) {

        echo '<div class="wc_input">';

        woocommerce_wp_text_input(
            array(
                'id'          => '_woo_toll_input',
                'label'       => __( 'Toll for this product', 'woocommerce' ),
                'placeholder' => '',
                'desc_tip'    => 'true',
                'description' => __( 'Enter the amount of toll for this product here in percent.', 'woo_uom' )
            )
        );
        echo '</div>';
    }

    /**
     * save meta value for the product
     * @param $post_id
     */

    public function save_field_input( $post_id ) {
        $woo_toll_input = isset( $_POST['_woo_toll_input'] ) ? sanitize_text_field( $_POST['_woo_toll_input'] ) : "";
        update_post_meta( $post_id, '_woo_toll_input', esc_attr( $woo_toll_input ) );
    }

    public function get_adjusted_price( $ID ) {
        $amount = get_post_meta($ID, '_woo_toll_input', true);

        if($amount == "" || floatval($amount) === 0){
            return 0;
        }

        $amount = floatval($amount);

        $product = wc_get_product($ID);

        $price = $product->get_price() * $amount / 100;

        return $price;
    }

    /**
     * display notification in the product category and single page
     */

    public function notification(){
        global $product;

        $amount = $this->get_adjusted_price($product->get_id());

        if($amount === 0){
            return;
        }

        echo sprintf( __( '<p class="toll-amount">You must pay a toll fee of <b>%s</b> if you order this product.</p>', 'woocommerce' ), wc_price($amount) );
    }

    /**
     * Notification in the cart page
     *
     * @param $total
     * @param $cart_item
     * @param $cart_item_key
     *
     * @return string
     */

    public function cart_notification( $total, $cart_item, $cart_item_key ) {
        $toll_message = "";

        $adjusted_price = $this->get_adjusted_price( $cart_item['product_id'] );

        if($adjusted_price !== 0){
            $toll_message = sprintf("<p class='toll-fee'>Toll fee: <span class='toll-fee-amount'>%s</span></p>", wc_price($adjusted_price));
        }

        return $total . $toll_message;
    }

    /**
     * Adjust cart before calculating total cart value
     * 
     * @param $cart_object
     */

    public function add_toll_price( $cart_object ) {

        foreach ( $cart_object->cart_contents as $key => $value ) {

            $adjusted_price = $this->get_adjusted_price($value['product_id']);

            if($adjusted_price !== 0){
                $price = floatval( $value['data']->get_price() );
                $value['data']->set_price($price + $adjusted_price);
            }

        }
    }
    public function product_toll_amount($atts){
        $atts = shortcode_atts( array(
            'type' => 'formatted',
            'ID' => ''
        ), $atts, 'product-toll-amount' );

        if( $atts['ID'] == ""){
            global $product;
            $ID = $product->get_id();
        }
        else{
            $ID = $attr['ID'];
        }

        $price = $this->get_adjusted_price($ID);

        return $atts['type'] !== "raw" ? wc_price($price) : $price;
    }
}

new Toll_On_Products();

将此代码保存在扩展名为.php 的文件中并上传到您的plugins 目录中,然后激活插件。或者您可以简单地将这段代码放在您的functions.php 文件中,但我不建议这样做。

您将在产品编辑页面中看到一个新字段:此产品的收费。以百分比输入金额,瞧。您会在产品类别页面、单个产品页面、购物车页面和结帐页面中看到一些通知。当然,这个金额将与产品价格相加。 如果您遇到任何困难,请发表评论。

【讨论】:

  • 感谢您的贡献。我不想在店里收过路费。在瑞典,我们在清关确定金额后自行支付通行费。我想要实现的是让我们的客户获得大约的通行费成本,这样他们就知道交货后会发生什么:) 这就是为什么我们可以根据要销售的产品设置不同的百分比非常重要的原因。 IE。婴儿车收费 2.7%,沙发收费 9%,依此类推。
  • 如果有办法不将费用添加到产品价格中,我认为您直接在产品中添加通行费的想法会奏效。只写百分比总和。最好使用短代码通过 Visual Composer 在 Wordpress/Woocommerce 中放置非常感谢!!
  • 那么在这种情况下,您可以简单地注释掉这一行 add_action( 'woocommerce_before_calculate_totals', array($this, 'add_toll_price') ); 或者可以将其删除。该功能负责将费用与产品价格相加。
  • 谢谢,它成功了。如何使用短代码打印百分比总和?
  • 将此简码 [product-toll-amount] 与您要向用户显示的文本一起使用。注意:此短代码将仅返回根据您在产品编辑页面中设置的百分比金额计算的价格
【解决方案2】:

你在寻找这样的东西吗?

const tollTiers = {
  2: .02,
  4: .04,
  6: .06
};

const products = [
  {name: 'Widget', toll: tollTiers[2], price: 100 },
  {name: 'Gadget', toll: tollTiers[4], price: 50 },
  {name: 'Cog', toll: tollTiers[6], price: 200 },
];

const list = document.querySelector('#products');

products.forEach((product) => {
  const price = product.price;
  const fee = price * product.toll;
  const total = price + fee;
  const li = document.createElement('li');
  const text = document.createTextNode(
    `${product.name} - $${price} + $${fee} (${product.toll * 100}%) toll = $${total}.`
  );
  li.appendChild(text);
  list.appendChild(li); 
});
&lt;ul id="products"&gt;&lt;/ul&gt;

【讨论】:

    【解决方案3】:

    要在档案页面和单个产品页面上显示您的动态计算通行费,请尝试:

    add_action('woocommerce_after_shop_loop_item_title','price_custom_label', 15 ); // Archives pages
    add_action('woocommerce_single_product_summary','price_custom_label', 15 ); // single product pages
    function price_custom_label(){
        global $product;
    
        $toll_fee = wc_price($product->get_price() * 2 / 100);
        $text = sprintf( __( 'You must pay a toll fee of %s if you order this product', 'woocommerce' ), $toll_fee );
        echo '<p>'. $text . '</p>';
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。

    经过测试并且有效。

    您应该需要调整它并设置它的样式。

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 2017-11-24
      • 1970-01-01
      • 2019-03-04
      相关资源
      最近更新 更多