php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2003字,纯文字阅读大概需要3分钟。
内容图文
![php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上](/upload/InfoBanner/zyjiaocheng/667/cd103c6868cd433a931923f41d8650f2.jpg)
我在主题主题的functions.php中使用以下代码在woocommerce单一产品页面上添加了一些自定义选项:
function options_on_single_product(){
?>
<input type="radio" name="option1" checked="checked" value="option1"> option 1 <br />
<input type="radio" name="option1" value="option2"> option 2
<?php
}
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product");
现在,我想在购物车页面上显示所选的选项值.请帮我做到这一点.
谢谢
解决方法:
这是将产品自定义字段存储在购物车对象中并在购物车和结帐页面中显示的完整代码:
// Output the Custom field in Product pages
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product", 1);
function options_on_single_product(){
?>
<label for="custom_field">
<input type="radio" name="custom_field" checked="checked" value="option1"> option 1 <br />
<input type="radio" name="custom_field" value="option2"> option 2
</label> <br />
<?php
}
// Stores the custom field value in Cart object
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_product_field_data', 10, 2 );
function save_custom_product_field_data( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['custom_field'] ) ) {
$cart_item_data[ 'custom_field' ] = $_REQUEST['custom_field'];
// below statement make sure every add to cart action as unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'my_order_data', $_REQUEST['custom_field'] );
}
return $cart_item_data;
}
// Outuput custom Item value in Cart and Checkout pages
add_filter( 'woocommerce_get_item_data', 'output_custom_product_field_data', 10, 2 );
function output_custom_product_field_data( $cart_data, $cart_item ) {
if( !empty( $cart_data ) )
$custom_items = $cart_data;
if( isset( $cart_item['custom_field'] ) ) {
$custom_items[] = array(
'key' => __('Custom Item', 'woocommerce'),
'value' => $cart_item['custom_field'],
'display' => $cart_item['custom_field'],
);
}
return $custom_items;
}
代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中.
此代码已经过测试并且可以工作.
内容总结
以上是互联网集市为您收集整理的php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上全部内容,希望文章能够帮你解决php-将产品自定义字段单选按钮值保存在购物车中并将其显示在购物车页面上所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。