根据 woocommerce 中的产品价格显示百分比

问题描述 投票:0回答:3

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

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

  • 产品价格:100美元
  • 过路费(2%):$2

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

公式:100 * 0,02

谢谢大家!

javascript wordpress woocommerce product-price
3个回答
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 <[email protected]>
* 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
文件中,但我不建议这样做。

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


1
投票

您在寻找这样的东西吗?

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); 
});
<ul id="products"></ul>


1
投票

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

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 文件中。

已测试且有效。

您应该需要对其进行调整并设计其样式。

© www.soinside.com 2019 - 2024. All rights reserved.