根据woocommerce中的产品价格显示%

时间:2018-02-07 15:50:58

标签: javascript wordpress woocommerce price

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

抱歉,但我无法在任何地方找到任何代码。

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

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

公式:100 * 0,02

谢谢你们!

3 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;

答案 1 :(得分: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文件。

经过测试和工作。

你应该对它进行调整并设计它。

答案 2 :(得分: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文件中,但我不建议这样做。

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