Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

javascript - Woocommerce实时计算:数量x get_meta('_ value')=最终值(Woocommerce live calculation : qty x get_meta('_value') = final value)

Here we are talking about selling products (especially pastry or food) in bulk unit / unit / or kg.(在这里,我们正在谈论以散装单位/单位/或千克的价格出售产品(尤其是糕点或食品)。)

All measurements are known weight and quantity,Therefore we must be able to estimate which product in kg will have how many units.(所有测量值都是已知的重量和数量,因此我们必须能够估计以千克为单位的哪种产品将具有多少个单位。) So I created an example of products just to test in woocommerce, I managed to realize my idea to estimate minimum qty of pieces (or any unit) per kg using a useful piece of code found here .(因此,我创建了一个仅用于woocommerce测试的产品示例,我设法实现了我的想法,即使用此处找到的有用代码来估算每公斤的最小数量(或任何单位)。) (1) I put it in a Snippet .((1)我将其放在代码段中 。) After that I started reading and trying to understand and follow the logic behind the code.(之后,我开始阅读并尝试理解和遵循代码背后的逻辑。) (2) Add some fonctions.((2) 添加一些功能。) just duplicated a few lines.. some copy / paste..(只是重复了几行..一些复制/粘贴..) (3) Try to put the same functions in product page (in progress no solution found)((3)尝试在产品页面中放置相同的功能(进行中,未找到解决方案)) Update 27/11/2016(更新27/11/2016) Revised code "I found an internal server error in checkout page "(修改后的代码“我在结帐页面中发现内部服务器错误 ”) I isolated the code that caused the error(我隔离了导致错误的代码) can someone explain what wrong with this part?(有人可以解释这部分有什么问题吗?) // Save and Display the order item weight (everywhere) add_action( 'woocommerce_checkout_create_order_line_item', 'display_order_item_data', 20, 4 ); function display_order_item_data( $item, $cart_item_key, $values, $order ) { if ( $values['data']->get_weight() > 0 ){ $item->update_meta_data( __( 'weight ', 'woocommerce' ), ( $cart_item['quantity'] * $cart_item['data']->get_weight() ) . ' ' . get_option('woocommerce_weight_unit') ); } } The Working part(工作部分) // Backend: Add and display a custom field for simple and variable products add_action( 'woocommerce_product_options_general_product_data', 'add_custom_price_field_to_general_product_data' ); function add_custom_price_field_to_general_product_data() { global $product_object; echo '<div class="options_group hide_if_external">'; woocommerce_wp_text_input(array( 'id' => '_min_unit_price', 'label' => __('Min Unit price', 'woocommerce') . ' (' . get_woocommerce_currency_symbol() . ')', 'description' => __('Enter the minimum unit price here.', 'woocommerce'), 'desc_tip' => 'true', 'value' => str_replace('.', ',', $product_object->get_meta('_min_unit_price') ), 'data_type' => 'price' )); // My custom field "Min price unit prefix" woocommerce_wp_text_input(array( 'id' => '_min_unit_prefix', 'label' => __('Min Unit prefix', 'woocommerce'), 'description' => __(' Enter prefix unit price here.', 'woocommerce'), 'desc_tip' => 'true', 'value' => str_replace('.', ',', $product_object->get_meta('_min_unit_prefix') ), 'data_type' => 'texte' )); // My custom field "Estimated quantity" woocommerce_wp_text_input(array( 'id' => '_estimated_quantity', 'label' => __('Estimated Quantity', 'woocommerce'), 'description' => __('Enter the quantity here.', 'woocommerce'), 'desc_tip' => 'true', 'value' => str_replace('.', ',', $product_object->get_meta('_estimated_quantity') ), 'data_type' => 'price' )); echo '</div>'; } // Backend: Save the custom field value for simple and variable products add_action( 'woocommerce_admin_process_product_object', 'save_product_custom_price_field', 10, 1 ); function save_product_custom_price_field( $product ) { if ( isset($_POST['_min_unit_price']) ) { $product->update_meta_data( '_min_unit_price', wc_clean( wp_unslash( str_replace( ',', '.', $_POST['_min_unit_price'] ) ) ) ); } if ( isset($_POST['_min_unit_prefix']) ) { $product->update_meta_data( '_min_unit_prefix', wc_clean( wp_unslash( str_replace( ',', '.', $_POST['_min_unit_prefix'] ) ) ) ); } if ( isset($_POST['_estimated_quantity']) ) { $product->update_meta_data( '_estimated_quantity', wc_clean( wp_unslash( str_replace( ',', '.', $_POST['_estimated_quantity'] ) ) ) ); } } // Frontend variable products: Display the min price with "From" prefix label add_filter( 'woocommerce_variable_price_html', 'custom_min_unit_variable_price_html', 10, 2 ); function custom_min_unit_variable_price_html( $price, $product ) { if( $min_unit_price = $product->get_meta('_min_unit_price') ){ $price = wc_price( wc_get_price_to_display( $product, array( 'price' => $min_unit_price ) ) ); $price .= $product->get_meta('_min_unit_prefix'); } return $price; } // Frontend simple products: Display the min price with "From" prefix label add_filter( 'woocommerce_get_price_html', 'custom_min_unit_product_price_html', 10, 2 ); function custom_min_unit_product_price_html( $price, $product ) { if( $product->is_type('simple') && $min_unit_price = $product->get_meta('_min_unit_price') ){ $price = wc_price( wc_get_price_to_display( $product, array( 'price' => $min_unit_price ) ) ); $price .= $product->get_meta('_min_unit_prefix'); } return $price; } // Display the cart item weight in cart and checkout pages add_filter( 'woocommerce_get_item_data', 'display_custom_item_data', 10, 2 ); function display_custom_item_data( $cart_item_data, $cart_item ) { if ( $cart_item['data']->get_weight() > 0 ){ $cart_item_data[] = array( 'name' => __( 'Weight subtotal', 'woocommerce' ), 'value' => ( $cart_item['quantity'] * $cart_item['data']->get_weight() ) . ' ' . get_option('woocommerce_weight_unit') ); } // Display the cart item "estimated quantity" in cart and checkout pages if ( $cart_item['data']->get_meta('_estimated_quantity') ){ $cart_item_data[] = array( 'name' => __( 'Estimated quantity ', 'woocommerce' ), 'value' => ( $cart_item['quantity'] * $cart_item['data']->get_meta('_estimated_quantity') ) ); } return $cart_item_data; } Now, I need help to understand how(现在,我需要帮助以了解如何) Estimated quantity: <? Php echo get_post_meta (get_the_ID (), '_estimated_quantity', true); ?> can Update in real time with the quantity of add_to_cart.(可以实时更新add_to_cart的数量。) the formula must be extremely simple in jQuery or javascript ?(该公式必须在jQuery或javascript中非常简单?) _estimated_quantity * quantity.(_估计数量*数量。) That all I need now.(那就是我现在所需要的。) To show to costumer how much they can get piece of cakes (or any others things) in 1 or xx kg(向客户显示以1公斤或xx公斤的价格可以得到多少蛋糕(或其他东西)) So I put a 15 or xx (approximate value) in backend.(因此,我在后端放置了15或xx(近似值)。) I hope it makes sense for you.(我希望这对您有意义。) For information I use clean install wordpress + elementor + elementor hello theme + woocommerce.(有关信息,我使用全新安装的wordpress + elementor + elementor hello主题+ woocommerce。) Update 27/11/2019 to Snuwerd(更新27/11/2019至Snuwerd) Thank you for trying to help me.(谢谢您的帮助。) I give you all the necessary informations on how I managed to integrate my codes.(我为您提供了有关如何集成代码的所有必要信息。) (as a beginner)((作为初学者)) I work exclusively with elementor pro and snippets.(我专门与elementor pro和片段一起工作。) with that I have everything I need to integrate (php, html, script, css, etc.) elementor is a theme editor, so I do not need to open any functions.php or other files.(这样,我就拥有了我需要集成的所有内容(php,html,脚本,css等)。elementor是主题编辑器,因此不需要打开任何functions.php或其他文件。) And the principal reason of course, I have to reuse them on other projects by import / export.(当然,主要原因是我必须通过导入/导出在其他项目上重用它们。) for themes I never use any.(对于主题,我从不使用任何主题。) I use only the hello elementor theme which is completely plain empty of any function, script or css.(我只使用了hello elementor主题,它完全没有任何函数,脚本或CSS。) How I integrate codes php and jquery / javascript(我如何整合代码php和jquery / javascript) Estimated quantity elements code(估计数量元素代码) Qty add to cart elements code(数量添加到购物车元素代码) update 28/11/2019(更新28/11/2019) Here the screenshot(<a href="https://stackoom.com/link/aHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS94VXNSUi5qcGc=" rel="n

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Welcome to Stack Overflow!(欢迎使用Stack Overflow!)

To answer your questions:(要回答您的问题:) "Verify that the code is valid"(“验证代码是否有效”) The code looks quite good (especially if this is really your first time messing with PHP)(代码看起来不错(特别是如果这确实是您第一次弄乱PHP)) "and (code) does not create problems in future woocommerce updates."(“并且(代码)在将来的woocommerce更新中不会产生问题。”) This question is really hard to answer.(这个问题真的很难回答。) "Now I am trying to put these two lines of information in the product page. via shortcode? or php again ?"(“现在,我正在尝试将这两行信息放入产品页面中。通过简码?还是再次使用php?”) Probably with more filters/actions, like you have done in the current code.(可能具有更多过滤器/操作,就像您在当前代码中所做的那样。) And if that doesn't seem possible, maybe by altering/overriding some template(s).(如果这似乎不可能,则可以通过更改/覆盖某些模板来实现。) Shortcodes don't necessarily make much sense, unless you want to insert the data into content area's in the backend when adding/editing products.(除非您想在添加/编辑产品时将数据插入后端的内容区域中,否则简码不一定有意义。) "Also improve the code"(“还改进代码”) This doesn't seem necessary.(这似乎没有必要。) "and add a prefix to Estimated Quantity."(“并在预估数量上添加前缀。”) Can you elaborate on what you mean by this?(您能详细说明一下这是什么意思吗?) ps.(ps。) I am probably off to bed soon, so I'll check again tomorrow.(我可能很快就要睡觉了,所以明天再检查一次。) Update(更新资料) I send qty and product_id to the server with AJAX and then the server gives back qty * _estimated_quantity;(我使用AJAX将qty和product_id发送到服务器,然后服务器返回qty * _estimated_quantity;) To get qty from the box on your screen and to set the right value in Estimated quantity , I need you to make a screenshot of their code.(为了从屏幕上的框中获取qty并在“ Estimated quantity设置正确的值,我需要您对其代码进行屏幕截图。) Open the page in Google Chrome, right click > inspect element on the quantity box and then make a screenshot of the code in the Elements tab.(在Google Chrome浏览器中打开该页面,右键单击>在数量框中检查元素,然后在“ Elements标签中制作代码的屏幕截图。) Also do the same for the Estimated quantity box (that has 15 in it in the screenshot).(也对“ Estimated quantity框(在屏幕快照中有15个)执行相同的操作。) I also assume your website is located on the root of your domain.(我还假设您的网站位于您域的根目录上。) So on www.example.com and not on www.example.com/wordpress/ (The Ajax call needs the right location).(因此,请访问www.example.com,而不要访问www.example.com/wordpress/(Ajax调用需要正确的位置)。) You can add this PHP to your functions.php(您可以将此PHP添加到您的functions.php) <?php add_action("wp_ajax_product_get_estimated_quantity", "product_get_estimated_quantity"); // calls our function if user is logged in add_action("wp_ajax_nopriv_product_get_estimated_quantity", "product_get_estimated_quantity"); // calls our function if user is not logged in, we do not do any security checks on which user etc though, but I don't think it's relevant in our case. function product_get_estimated_quantity () { $product_id = $_REQUEST["product_id"]; if (!is_numeric($product_id)) { // check if really a number, for security purposes die(); } $qty = $_REQUEST["qty"]; if (!is_numeric($qty)) { // check if really a number, for security purposes die(); } // No need to get product object, can get metadata directly with get_post_meta // // get estimated_quantity per kg by product_id // $args = array( // 'include' => array( $product_id ), // ); // $products = wc_get_products( $args ); // foreach ($products as $product) { // } // echo $product->get_id(); $estimated_quantity_per_kg = get_post_meta( $product_id, '_estimated_quantity', true); // $estimated_quantity_per_kg = 15; // this line is only for my local testing, since my products dont have _estimated_quantity meta echo ((int) $estimated_quantity_per_kg) * ((int) $qty); die(); } ?> And add this javascript/jquery anywhere you can (assuming that you know how to, its also easy to find out with google (How to add javascript to Wordpress)).(并在任何可能的地方添加此javascript / jquery(假设您知道该怎么做,使用google也很容易找到它(如何将Javascript添加到Wordpress))。) jQuery(document).ready(function($) { if( $('body.single-product').length) { // if on a single product page $( document ).on( 'change', '.quantity input[type=number]', function() { // selector for the qty box is probably already correct var qty = $( this ).val(); var product_id = $(this).closest('.product').attr('id'); product_id = product_id.split('-'); product_id = product_id[1]; jQuery.ajax({ type : "post", dataType : "json", url : '/wp-admin/admin-ajax.php', // only works if Wordpress is installed in root of your domain. if you installed in www.example.com/wordpress/, then add /wordpress/ before this data : {action: "product_get_estimated_quantity", product_id : product_id, qty: qty}, success: function(response) { // right click -> inspect element to find the right selector for estimated quantity (the 15 from your photoshop) response = parseInt(response); $('#snuwerd > div').val('Estimated quantity: ' + response); } }); return false; }); } }); In case you want to know how I added the javascript, i made a file in child-theme-directory/js/child.js.(如果您想知道如何添加JavaScript,我在child-theme-directory / js / child.js中创建了一个文件。) Then added the Jquery to it.(然后向其中添加Jquery。) And then I added this to functions.php :(然后我将其添加到functions.php :) function theme_enqueue_child_scripts() { $file = '/js/child.js'; $cache_buster = date("YmdHis", filemtime( get_stylesheet_directory() . $file )); // no uri wp_enqueue_script( 'child', get_stylesheet_directory_uri() . $file, array( 'jquery' ), $cache_buster, true ); // true = footer } add_action( 'wp_enqueue_scripts', 'theme_enqueue_child_scripts' ); Update(更新资料) I added the selector for the Estimated quantity field in the javascript, and the quantity selector was already correct, so please re-copy the javascript.(我在javascript中为“估计数量”字段添加了选择器,并且数量选择器已经正确,因此请重新复制javascript。) I looked at the screenshot where you add in JS and PHP, but the way you add PHP is not good enough for this PHP.(我看了您在其中添加JS和PHP的屏幕截图,但是添加PHP的方式对于此PHP来说还不够好。) Where you add PHP in the screenshot, it only counts for that page and it needs to be sidewide.(在屏幕快照中添加PHP的位置,它仅计入该页面,并且需要横向放置。) The Ajax call will not be able to access PHP that is added to a specific page.(Ajax调用将无法访问添加到特定页面的PHP。) If Elementor doesn't have a side wide place to add PHP and if you don't want to change the functions.php of your theme, then maybe you can use this plugin: https://wordpress.org/plugins/my-custom-functions/ .(如果Elementor没有足够的地方添加PHP,并且您不想更改主题的functions.php ,则可以使用此插件: https : //wordpress.org/plugins/my-自定义功能/ 。) Also, don't forget to actually add the PHP I provided, I didn't see it in your JS/PHP screenshot.(另外,不要忘记实际添加我提供的PHP,在您的JS / PHP屏幕截图中也没有看到它。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...