Complicated Woocommerce shipping Rules issue - woocommerce

I am trying to apply complicated shipping rules in Woocommerce.
I have basic products which is:
Spend
Shipping cost
less than 300
30$
300 or more
Free
But I also have some large products and products with special delivery requirements
product
Shipping Class
cost
large box
Truck with crane
1000$
large Box
Truck only
200$
Gazebo (Choice1: Delivery Only)
Delivery & Assebly
200$
Gazebo (Choice2: Delivery & Assembly)
Delivery & Assebly
350$
Below is my shipping methods
Shipping Methods
Standerd rates
Shipping With Assembly
For basic products everything is working well,
Also for large boxes its well as it shows in Standard shipping.
But when I add the (shipping with assembly) shipping method it still appear as choice even if no product with this class is in the cart.
I just need it to appear only when gazebo is in the cart
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_class_is_in_cart', 100, 2 );
function hide_shipping_when_class_is_in_cart( $rates, $package ) {
$free_shipping_method = 'free_shipping:13';
$shipping_classes = array('truck-crane','large-furniture','furniture-assembly');
$class_exists = false;
$cart_classes = array();
$shipping_methods = $shipping_zone->get_shipping_methods();
foreach( $package['contents'] as $cart_item )
$cart_item_class = $cart_item['data']->get_shipping_class();
if( in_array($cart_item_class , $shipping_classes ) ) {//Check if any shipping class exist
array_push($cart_classes,$cart_item_class); //push cart classes to array
$class_exists = true;
//break;
}
foreach($shipping_methods as $method){
$method_classes = $method->get_shipping_classes();
//Here i want to unset shipping methods which has no avaiable class in cart items
}
if( $class_exists )
unset( $rates[$free_shipping_method] );
return $rates;
}

I ended up adding the service like 'assembly' as a choice that comes with the product
my code below
/**
** Display Fields
*/
add_action('woocommerce_product_options_shipping', 'woocommerce_product_custom_product_service');
function woocommerce_product_custom_product_service()
{
global $woocommerce, $post;
echo '<div class="product_custom_field"><span class="wrap">';
woocommerce_wp_text_input(
array(
'id' => '_custom_product_service_label',
'placeholder' => 'Service Label',
'label' => __('Custom Service', 'woocommerce'),
)
);
woocommerce_wp_text_input(
array(
'id' => '_custom_product_service_fees',
'placeholder' => 'Service Fees',
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
echo '</span></div>';
}
/**
** Save Fields
*/
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_product_service_save');
function woocommerce_product_custom_product_service_save($post_id)
{
$woocommerce_custom_product_service_label = $_POST['_custom_product_service_label'];
$woocommerce_custom_product_service_fees = $_POST['_custom_product_service_fees'];
if (!empty($woocommerce_custom_product_service_label) && !empty($woocommerce_custom_product_service_fees)){
update_post_meta($post_id, '_custom_product_service_label', esc_attr($woocommerce_custom_product_service_label));
update_post_meta($post_id, '_custom_product_service_fees', esc_attr($woocommerce_custom_product_service_fees));
}elseif(empty($woocommerce_custom_product_service_label) && empty($woocommerce_custom_product_service_fees)){
update_post_meta($post_id, '_custom_product_service_label', '');
update_post_meta($post_id, '_custom_product_service_fees', '');
}
}
/**
** Product page form
*/
add_action('woocommerce_single_product_summary','add_custom_product_service_to_single_product', 2 );
function add_custom_product_service_to_single_product(){
global $product;
if( !$product->get_meta( '_custom_product_service_label' ) && !$product->get_meta( '_custom_product_service_fees' )) return;
add_action('woocommerce_before_add_to_cart_button', 'add_custom_product_service_option', 30 );
}
function add_custom_product_service_option(){
global $product;
$active_price = (float) $product->get_price();
$service_label = $product->get_meta( '_custom_product_service_label' );
$service_price = (float) $product->get_meta( '_custom_product_service_fees' );
$service_price_html = strip_tags( wc_price( wc_get_price_to_display( $product, array('price' => $service_price ) ) ) );
$active_price_html = wc_price( wc_get_price_to_display( $product ) );
$disp_price_sum_html = wc_price( wc_get_price_to_display( $product, array('price' => $active_price + $service_price ) ) );
echo '<div class="hidden-field">
<p class="form-row form-row-wide" id="service_option_field" data-priority="">
   <span class="woocommerce-input-wrapper"><label class="checkbox"> ' .$service_label.' '.__("Service:", "Woocommerce") .
' <input type="checkbox" class="input-checkbox " name="service_option" id="service_option" value="1"> +' . $service_price_html .
'</label></span></p>
<input type="hidden" name="service_price" value="' . $service_price . '">
<input type="hidden" name="active_price" value="' . $active_price . '"></div>';
// Jquery: Update displayed price
?>
<script type="text/javascript">
jQuery(function($) {
var cb = 'input[name="service_option"]'
pp = 'p.price';
// On change / select a variation
$('form.cart').on( 'change', cb, function(){
if( $(cb).prop('checked') === true )
               $(pp).html('<?php echo $disp_price_sum_html.__("(Assembly Included)", "Woocommerce"); ?>');
else
$(pp).html('<?php echo $active_price_html; ?>');
})
});
</script>
<?php
}
/**
** Add to Cart
*/
add_filter('woocommerce_add_cart_item_data', 'add_custom_product_service_data', 10, 3);
function add_custom_product_service_data( $cart_item_data, $product_id, $variation_id ) {
if (isset($_POST['service_option']) && !empty($_POST['service_option'])) {
$cart_item_data['new_price'] = (float) ($_POST['active_price'] + $_POST['service_price']);
$cart_item_data['service_price'] = (float) $_POST['service_price'];
$cart_item_data['active_price'] = (float) $_POST['active_price'];
foreach(WC()->cart->get_cart() as $cart_item){
if(($product_id == $cart_item['product_id']) && !empty($cart_item['service_price'])){
$unique_key = $cart_item['unique_key'];
break;
}
}
if(!empty($unique_key)){
$cart_item_data['unique_key'] = $unique_key;
}else{
$cart_item_data['unique_key'] = md5(microtime().rand());
}
return $cart_item_data;
}}
/**
** Set the new calculated cart item price
*/
add_action('woocommerce_before_calculate_totals', 'add_custom_product_service_custom_price', 20, 1);
function add_custom_product_service_custom_price($cart) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach($cart->get_cart() as $cart_item) {
if (isset($cart_item['new_price']))
$cart_item['data']->set_price((float) $cart_item['new_price']);
}
}
/**
** Display in Cart
*/
add_filter('woocommerce_get_item_data', 'display_custom_product_service_item_data', 10, 2);
function display_custom_product_service_item_data($cart_item_data, $cart_item) {
$_product = new WC_Product( $cart_item['product_id'] );
$service_label = $_product->get_meta( '_custom_product_service_label' );
if (isset($cart_item['service_price'])) {
//$service_label = get_post_meta( $cart_item['product_id'], '_custom_product_service_label' );
$cart_item_data[] = array(
'name' => $service_label .__(" Service Fees", "woocommerce"),
'value' => strip_tags( '+ ' . wc_price( wc_get_price_to_display( $cart_item['data'], array('price' => $cart_item['service_price'] ) ) ) )
);
}elseif(!empty($service_label)){
$cart_item_data[] = array(
'name' => $service_label .__(" Service Not Included", "woocommerce"),
'value' => strip_tags( '+ ' . wc_price( wc_get_price_to_display( $cart_item['data'], array('price' => $cart_item['service_price'] ) ) ) )
);
}
return $cart_item_data;
}

Related

Save multiple datas in order WooCommerce

I have two customs fields in my product (image and texte), I all ready show it in the cart but when the order is complete, i can't find how can I show both in the admin order (I can show one of two ^^)
Here is the code :
// Add custom fields data as the cart item custom data
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_fields_data_as_custom_cart_item_data', 10, 2 );
function add_custom_fields_data_as_custom_cart_item_data($cart_item, $product_id){
if( isset($_FILES['image']) && !empty($_FILES['image']) && !empty($_POST['nom_pp']) ) {
$upload = wp_upload_bits( $_FILES['image']['name'], null, file_get_contents( $_FILES['image']['tmp_name'] ) );
$filetype = wp_check_filetype( basename( $upload['file'] ), null );
$upload_dir = wp_upload_dir();
$upl_base_url = is_ssl() ? str_replace('http://', 'https://', $upload_dir['baseurl']) : $upload_dir['baseurl'];
$base_name = basename( $upload['file'] );
$cart_item['file_upload'] = array(
'guid' => $upl_base_url .'/'. _wp_relative_upload_path( $upload['file'] ), // Url
'file_type' => $filetype['type'], // File type
'file_name' => $base_name, // File name
'title' => ucfirst( preg_replace('/\.[^.]+$/', '', $base_name ) ), // Title
);
$cart_item['nom_pp'] = $_POST['nom_pp'];
$cart_item['unique_key'] = md5( microtime().rand() ); // Avoid merging items
}
return $cart_item;
}
// Display custom cart item data in cart (optional)
add_filter('woocommerce_get_item_data', 'njengah_custom_item_data', 10, 2);
function njengah_custom_item_data($cart_item_data, $cart_item) {
if ( isset($cart_item['file_upload']['title']) ){
$cart_item_data[] = array(
'name' => __( 'Mon image ', 'woocommerce' ),
'value' => str_pad($cart_item['file_upload']['title'], 16, 'X', STR_PAD_LEFT) . '…',
);
}
if ( isset($cart_item['nom_pp']) ){
$cart_item_data[] = array(
'name' => __( 'Nom du papier peint ', 'woocommerce' ),
'value' => $cart_item['nom_pp'],
);
}
return $cart_item_data;
}
// Save Image data as order item meta data
add_action( 'woocommerce_checkout_create_order_line_item', 'njengah_field_update_order_item_meta', 20, 4 );
function njengah_field_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( isset($values['file_upload']) && isset($values['nom_pp']) ){
$item->update_meta_data($item, '_img_file', $values['file_upload']);
$item->update_meta_data($item, '_nom_pp', $values['nom_pp']);
}
}
// Admin orders: Display a linked button + the link of the image file
add_action( 'woocommerce_after_order_itemmeta', 'njengah_image_link_after_order_itemmeta', 10, 3 );
function njengah_image_link_after_order_itemmeta( $item_id, $item, $product ) {
// Only in backend for order line items (avoiding errors)
if( is_admin() && $item->is_type('line_item') && $file_data = $item->get_meta('_img_file') && $file_data = $item->get_meta('_nom_pp') ){
echo '<p>'.__("Voir l'image") . '</p>'; // Optional
echo '<p><code>'.$file_data['guid'].'</code></p>'; // Optional
echo '<p>'.$file_data['nom_pp'].'</p>'; // Optional
}
}
I think I need to edit the order meta data, but I don't know how can I do it :)

Add a WooCommerce checkout checkbox field that enable a discount based on product quantity

Based on Add a checkout checkbox field that enable a percentage fee in Woocommerce answer code, I've got a custom checkbox on which I need to offer discount to customers.
I'm trying to apply the custom discount of say $0.03 x product quantity e.g.
If quantity is 50 then the discount would be 50 x $0.03 = $1.5
Right now, it's deducting $0.03 from the Cart Total. Can anyone help me with achieving the required results?
Here is my code attempt:
// Add a custom checkbox fields after billing fields
add_action( 'woocommerce_after_checkout_billing_form', 'add_custom_checkout_checkbox', 20 );
function add_custom_checkout_checkbox(){
// Add a custom checkbox field
woocommerce_form_field( 'discount30', array(
'type' => 'checkbox',
'label' => __(' Senior'),
'class' => array( 'form-row-wide' ),
), '' );
}
// Remove "(optional)" label on "Installement checkbox" field
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'discount30' === $key && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) .
')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_fee_script' );
function checkout_fee_script() {
// Only on Checkout
if( is_checkout() && ! is_wc_endpoint_url() ) :
if( WC()->session->__isset('enable_fee') )
WC()->session->__unset('enable_fee')
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on('change', 'input[name=discount30]', function(e){
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'enable_fee',
'enable_fee': fee,
},
success: function (result) {
$('body').trigger('update_checkout');
},
});
});
});
</script>
<?php
endif;
}
// Get Ajax request and saving to WC session
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
function get_enable_fee() {
if ( isset($_POST['enable_fee']) ) {
WC()->session->set('enable_fee', ($_POST['enable_fee'] ? true : false) );
}
die();
}
// Add a custom 3 Cents Discount
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount', 20, 1 );
function custom_discount( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
return;
$discount = -0.03;
if( WC()->session->get('enable_fee') )
$cart->add_fee( __( 'Discount', 'woocommerce'), ( $discount ) );
}
To determine the discount based on the number of items in the cart, you can use WC()->cart->get_cart_contents_count();
Which then can be applied in the woocommerce_cart_calculate_fees action hook.
So you get:
// Add a custom checkbox fields after billing fields
function action_woocommerce_after_checkout_billing_form( $checkout ) {
// Add a custom checkbox field
woocommerce_form_field( 'discount30', array(
'type' => 'checkbox',
'label' => __( ' Senior', 'woocommerce' ),
'class' => array( 'form-row-wide' ),
), '' );
}
add_action( 'woocommerce_after_checkout_billing_form', 'action_woocommerce_after_checkout_billing_form', 10, 1 );
// Remove "(optional)" label on "discount30" field
function filter_woocommerce_form_field( $field, $key, $args, $value ) {
// Only on checkout page
if ( $key === 'discount30' && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
add_filter( 'woocommerce_form_field' , 'filter_woocommerce_form_field', 10, 4 );
// jQuery - Ajax script
function action_wp_footer() {
// Only on Checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
if ( WC()->session->__isset('enable_fee') )
WC()->session->__unset('enable_fee')
?>
<script type="text/javascript">
jQuery( function($){
if ( typeof wc_checkout_params === 'undefined' )
return false;
$( 'form.checkout' ).on( 'change', 'input[name=discount30]', function(e) {
var fee = $(this).prop('checked') === true ? '1' : '';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'enable_fee',
'enable_fee': fee,
},
success: function (result) {
$('body').trigger('update_checkout');
},
});
});
});
</script>
<?php
endif;
}
add_action( 'wp_footer', 'action_wp_footer' );
// Get Ajax request and saving to WC session
function get_enable_fee() {
if ( isset($_POST['enable_fee']) ) {
WC()->session->set( 'enable_fee', ( $_POST['enable_fee'] ? true : false ) );
}
die();
}
add_action( 'wp_ajax_enable_fee', 'get_enable_fee' );
add_action( 'wp_ajax_nopriv_enable_fee', 'get_enable_fee' );
// Add a custom 3 Cents Discount
function action_woocommerce_cart_calculate_fees( $cart ) {
// Only on checkout
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_checkout() )
return;
// Get number of items in the cart.
$items_in_cart = $cart->get_cart_contents_count();
// Calculate
$discount = 0.03 * $items_in_cart;
// Apply discount
if ( WC()->session->get('enable_fee') ) {
$cart->add_fee( __( 'Discount', 'woocommerce' ), -$discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
Note: to get the number of products in cart opposite the number of items in cart
Change
// Get number of items in the cart.
$items_in_cart = $cart->get_cart_contents_count();
// Calculate
$discount = 0.03 * $items_in_cart;
To
// Products in cart
$products_in_cart = count( $cart->get_cart() );
// Calculate
$discount = 0.03 * $products_in_cart;

Add custom select field with validation to WooCommerce checkout page if certain products are in cart

I wish to add a custom select field with validation to the WooCommerce checkout page if certain products are in cart.
With my current code I retrieve the value of my custom WooCommerce form field. However, it display "array" at the order page.
I have an select field which have an option of 1 and 0. Upon selection of the select field, i want it to display either 1 or 0 at the order page but im unable to do so.
Please guide me on what should i do with my current codes:
//AMBASSADOR CUSTOM CHECKOUT FIELDS, CONTENT add marketplace for sameday TEST
add_action( 'woocommerce_after_checkout_billing_form', 'aym_custom_checkout_field' );
function aym_custom_checkout_field( $checkout ) {
//Check if Product in Cart
$prod_in_cart_17563 = aym_is_conditional_product_in_cart_17563( 212 );
if ( $prod_in_cart_17563 === true ) {
$domain = 'wocommerce';
$default = 'Y';
woocommerce_form_field( '_my_field_name', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Market Place - Please Select Y to complete this order' ),
'required' => true,
'options' => array(
'Y' => __('1'),
'N' => __('0')
),'default' => $default),
$checkout->get_value( '_my_field_name' ) );
}
}
//AMBSSADOR BUNDLE add marketplace for same day pa rt 2
function aym_is_conditional_product_in_cart_17563( $product_id ) {
//Check to see if user has product in cart
global $woocommerce;
//flag no product in cart
$prod_in_cart_17563 = false;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id === $product_id ) {
//product is in cart!
$prod_in_cart_17563 = true;
}
}
return $prod_in_cart_17563;
}
//process orders in order page
// Custom checkout fields validation
add_action( 'woocommerce_checkout_process', 'custom_checkout_field_process' );
function custom_checkout_field_process() {
if ( isset($_POST['_my_field_name']) && empty($_POST['_my_field_name']) )
wc_add_notice( __( 'Please fill in "My 1st new field".' ), 'error' );
}
// Save custom checkout fields the data to the order
add_action( 'woocommerce_checkout_create_order', 'custom_checkout_field_update_meta', 10, 2 );
function custom_checkout_field_update_meta( $order, $data ){
if( isset($_POST['_my_field_name']) && ! empty($_POST['_my_field_name']) )
$order->update_meta_data( '_my_field_name', sanitize_text_field( $_POST['_my_field_name'] ) );
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['_my_field_name']) update_post_meta( $order_id, 'My Field', esc_attr($_POST['_my_field_name']));
}
// View fields in Edit Order Page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_custom_fields_value_admin_order', 10, 1 );
function display_custom_fields_value_admin_order( $order ){
// Display the delivery option
if( $delivery_option = $order->get_meta('_my_field_name') )
echo '<p><strong>'.__('Delivery type').':</strong> ' . $delivery_option . '</p>';
}
// Display field value on the order edit page
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta( $order ) {
if( $selectoption = $order->get_meta('_my_field_name') ) {
//$value = wc_get_hearaboutus_options()[$selectoptions];
$meta= get_post_meta( $post->ID, $selectoption, true );
$myvalues = unserialize( $meta );
echo '<p><strong>'.__('Market_Place').':</strong> ' . $myvalues . '</p>';
}
}
I have partly rewritten / modified your code with some (extra) features
The ability to check for multiple product IDs in the shopping cart
The custom field is only added if a certain product id is in the shopping cart
The possibility to check out if the custom field is not present (product ID is NOT in cart)
No possibility to checkout as long as the value 'Y' is not selected from the custom select menu (Product ID is IN cart)
Explanation via comment tags added in the code
// Add custom 'select' field after checkout billing form (if product ID is in cart)
function action_woocommerce_after_checkout_billing_form( $checkout ) {
// Check if Product in Cart
// Multiple product IDs can be entered, separated by a comma
$product_in_cart = is_product_in_cart( array( 212, 30, 815 ) );
// True
if ( $product_in_cart ) {
$domain = 'woocommerce';
$default = 'Y';
woocommerce_form_field( '_my_field_name', array(
'type' => 'select',
'class' => array( 'form-row-wide' ),
'label' => __( 'Market Place - Please Select Y to complete this order', $domain ),
'required' => true,
'options' => array(
'Y' => __( 'Y', $domain ),
'N' => __( 'N', $domain ),
),
'default' => $default,
), $checkout->get_value( '_my_field_name' ) );
}
}
add_action( 'woocommerce_after_checkout_billing_form', 'action_woocommerce_after_checkout_billing_form', 10, 1 );
// Function to check if a certain product ID is in cart
function is_product_in_cart( $targeted_ids ) {
// Flag no product in cart
$flag = false;
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids
if ( in_array( $cart_item['product_id'], $targeted_ids ) ) {
// Product is in cart
$flag = true;
// Break loop
break;
}
}
}
return $flag;
}
// Custom checkout 'select' field validation
function action_woocommerce_checkout_process() {
// Isset
if ( isset( $_POST['_my_field_name'] ) ) {
$domain = 'woocommerce';
$my_field_name = $_POST['_my_field_name'];
// Empty
if ( empty ( $my_field_name ) ) {
wc_add_notice( __( 'Please Select Y to complete this order', $domain ), 'error' );
}
// NOT empty but value is 'N'
if ( ! empty ( $my_field_name ) && $my_field_name == 'N' ) {
wc_add_notice( __( 'Please Select Y to complete this order', $domain ), 'error' );
}
}
}
add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );
// Save custom checkout 'select' field
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset
if ( isset( $_POST['_my_field_name'] ) ) {
$my_field_name = $_POST['_my_field_name'];
// NOT empty & equal to 'Y'
if ( ! empty( $my_field_name ) && $my_field_name == 'Y' ) {
$order->update_meta_data( '_my_field_name', sanitize_text_field( $my_field_name ) );
}
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );
// Display the custom 'select' field value on admin order pages after billing adress
function action_woocommerce_admin_order_data_after_billing_address( $order ) {
$domain = 'woocommerce';
// Get meta
$my_field_name = $order->get_meta( '_my_field_name' );
// NOT empty
if ( ! empty ( $my_field_name ) ) {
echo '<p><strong>' . __( 'Delivery type', $domain ) . ':</strong> ' . $order->get_meta( '_my_field_name' ) . '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );
// Display the custom 'select' field value on 'order received' and 'order view' pages (frontend)
function action_woocommerce_order_details_after_order_table( $order ) {
$domain = 'woocommerce';
// Get meta
$my_field_name = $order->get_meta( '_my_field_name' );
// NOT empty
if ( ! empty ( $my_field_name ) ) {
echo '<p><strong>' . __( 'Delivery type', $domain ) . ':</strong> ' . $order->get_meta( '_my_field_name' ) . '</p>';
}
}
add_action( 'woocommerce_order_details_after_order_table', 'action_woocommerce_order_details_after_order_table', 10, 1 );

Woocommerce - Calculate Exta Fee Based on Amount of People

I've added in a function for a custom field on the product general options:
// Add Custom Field to Product under General
function create_extra_fee_field() {
$args = array(
'id' => 'park_fee',
'label' => __( 'Natl Park Entrance Fee', 'tranq-lsx-child' ),
'class' => 'tranq-custom-field',
'desc_tip' => true,
'description' => __( 'This sets the Fee that will be added to the car.', 'tranq-lsx-child' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_general_product_data', 'create_extra_fee_field' );
// Save Custom Field Data
function save_extra_fee_field( $post_id ) {
$product = wc_get_product( $post_id );
$title = isset( $_POST['park_fee'] ) ? $_POST['park_fee'] : '';
$product->update_meta_data( 'park_fee', sanitize_text_field( $title ) );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'save_extra_fee_field' );
I would like to add this as an extra fee to the Cart Totals which multiplied based on the amount of Person/People that were selected from the Woocommerce Bookings.
Something like this:
// Calculate Extra Fee Based on Amount of People.
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
function add_custom_fees( WC_Cart $cart ){
$park_fee = get_post_meta($item['product_id'] , 'park_fee', true);
foreach( $cart->get_cart() as $item ){
$fees += $item[ 'park_fee' ] * 14706;
}
if( $fees != 0 ){
$cart->add_fee( 'Park Fee', $fees);
}
}
How do I go about in achieving this? Any Links to a walkthrough would be greatly appreciated.
I've added this and it seems to work:
// Add Custom Field to Cart Totals
function woo_add_cart_fee() {
global $woocommerce;
foreach( WC()->cart->get_cart() as $cart_item ){
// Get the WC_Product object (instance)
$product = $cart_item['data'];
$product_id = $product->get_id(); // get the product ID
$custom_field_value = get_post_meta( $product->get_id(), 'park_fee', true );
$person = array_sum( $cart_item['booking']['_persons'] );
}
$additional_fee_name = "Natl Park Entrance Fee";
$extra_fee = $custom_field_value * $person;
$addedFee = false;
// first check to make sure it isn’t already there
foreach ( $woocommerce->cart->get_fees() as $_fee )
{
if ($_fee->id == sanitize_title($additional_fee_name) )
{
$_fee->amount = (float) esc_attr( $extra_fee );
}
}
if (!$addedFee)
{
$woocommerce->cart->add_fee( __($additional_fee_name, "woocommerce"),
$extra_fee, $additional_fee_taxable );
}
}
add_action( "woocommerce_before_calculate_totals", "woo_add_cart_fee" );

Create custom notification in post insert in buddypress

I want to add custom notification in the time of post creation. I have followed this url https://webdevstudios.com/2015/10/06/buddypress-adding-custom-notifications/
What i have done, I am adding custom notification in creation of project or bid post type. But it not working. Please check my code and let me what i have done wrong.
// this is to add a fake component to BuddyPress. A registered component is needed to add notifications
function custom_filter_notifications_get_registered_components( $component_names = array() ) {
// Force $component_names to be an array
if ( ! is_array( $component_names ) ) {
$component_names = array();
}
// Add 'custom' component to registered components array
array_push( $component_names, 'projectadd' );
// Return component's with 'custom' appended
return $component_names;
}
add_filter( 'bp_notifications_get_registered_components', 'custom_filter_notifications_get_registered_components' );
// this hooks to post creation and saves the post id
function bp_custom_add_notification( $post_id, $post ) {
if ( $post->post_type == 'project' || $post->post_type == 'bid' ) {
$post = get_post( $post_id );
$author_id = $post->post_author;
bp_notifications_add_notification( array(
'user_id' => $author_id,
'item_id' => $post_id,
'component_name' => 'projectadd',
'component_action' => 'projectadd_action',
'date_notified' => bp_core_current_time(),
'is_new' => 1,
) );
}
}
add_action( 'wp_insert_post', 'bp_custom_add_notification', 99, 2 );
// this gets the saved item id, compiles some data and then displays the notification
function custom_format_buddypress_notifications( $content, $item_id, $secondary_item_id, $total_items, $format = 'string', $action, $component ) {
// New custom notifications
if ( 'projectadd_action' === $action ) {
$post = get_post( $item_id );
$custom_title = $post->post_author . ' add the project ' . get_the_title( $item_id );
$custom_link = get_permalink( $post );
$custom_text = $post->post_author . ' add the project ' . get_the_title( $item_id );
// WordPress Toolbar
if ( 'string' === $format ) {
$return = apply_filters( 'projectadd_filter', '' . esc_html( $custom_text ) . '', $custom_text, $custom_link );
// Deprecated BuddyBar
} else {
$return = apply_filters( 'projectadd_filter', array(
'text' => $custom_text,
'link' => $custom_link
), $custom_link, (int) $total_items, $custom_text, $custom_title );
}
return $return;
}
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 7 );
You've changed the number and order of arguments from the example you linked. The two arguments you added are never used. Restore the arguments in the function to match the example and the the number in your add_filter to 5.
function custom_format_buddypress_notifications( $content, $item_id, $secondary_item_id, $total_items, $format = 'string', $action, $component )
{
...
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 7 );
needs to be
function custom_format_buddypress_notifications( $action, $item_id, $secondary_item_id, $total_items, $format = 'string' )
{
...
}
add_filter( 'bp_notifications_get_notifications_for_user', 'custom_format_buddypress_notifications', 10, 5 );

Resources