Woocommerce product adons update price programatically - wordpress

I'm setting up WooCommerce bookings with the WooCommerce Product Add-Ons plugin to make a bookable product with pickup and return time.
It works pretty well but the only issue is the corresponding price will not automatically update when the customer will change the time which is made with WooCommerce Product Add-Ons plugin.
It only updates when the booking calendar is changed. Here is the custom code.
add_filter( 'booking_form_calculated_booking_cost', 'wdm_add_hotel_booking', 10, 3);
function wdm_add_hotel_booking( $cost, $book_obj, $posted ) {
$product = wc_get_product($posted['add-to-cart'] );
$product_id = $posted['add-to-cart'];
$qntytxt = $product_id+1;
$qnty = $posted['wc_bookings_field_persons_'.$qntytxt];
$product = wc_get_product( $product_id );
$rent = $product->get_price();
$start_date_month = $posted['wc_bookings_field_start_date_month'];
$start_date_day = $posted['wc_bookings_field_start_date_day'];
$start_date_year = $posted['wc_bookings_field_start_date_year'];
$to_date_month = $posted['wc_bookings_field_start_date_to_month'];
$to_date_day = $posted['wc_bookings_field_start_date_to_day'];
$to_date_year = $posted['wc_bookings_field_start_date_to_year'];
$time = strtotime($start_date_month.'/'.$start_date_day.'/'.$start_date_year);
$fromDate = date('Y-m-d',$time);
if($to_date_month !=""){
$time = strtotime($to_date_month.'/'.$to_date_day.'/'.$to_date_year);
$ToDate = date('Y-m-d',$time);
}else{
$ToDate = $fromDate;
}
$pickup_time = $posted['addon-'.$product_id.'-pick-up-time-0'];
$return_time = $posted['addon-'.$product_id.'-return-time-1'];
if(isset($pickup_time) && ($pickup_time!="")){
$ptimeRange = explode("-",$pickup_time);
$ptimeRangelevel = $ptimeRange[2];
}
if(isset($return_time) && ($return_time!="")){
$rtimeRange = explode("-",$return_time);
$rtimeRangelevel = $rtimeRange[2];
}
if($ptimeRangelevel!="" && $rtimeRangelevel!=""){
$ts1 = strtotime($fromDate);
$ts2 = strtotime($ToDate);
$timeDiff = abs($ts2 - $ts1);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
if ($rtimeRangelevel<=$ptimeRangelevel){
if($numberDays>0){
$ActuvalCnt = $numberDays;
$ActualPrice = $ActuvalCnt * $qnty * $rent;
if($rtimeRangelevel < $ptimeRangelevel) {
if($numberDays>1){
$cost = $ActualPrice;
$ActualPrice = $ActuvalCnt * $qnty * $rent;
$cost = $cost - $ActualPrice;
if ($rtimeRangelevel < $ptimeRangelevel) {
echo $ActualPrice = ($ActuvalCnt + 1 ) * $qnty * $rent;
$cost = $ActualPrice - ($rent*$qnty);
}
}else{
$ActualPrice = $ActuvalCnt * $qnty * $rent;
$cost = $cost - $ActualPrice;
}
}else{
$ActualPrice = $ActuvalCnt * $qnty * $rent;
$cost = $ActualPrice;
}
}
} else {
$ActuvalCnt = $numberDays + 1;
if (($ActuvalCnt > 2) && ($rtimeRangelevel != $ptimeRangelevel)){
$ActualPrice = $ActuvalCnt * $qnty * $rent;
$cost = $ActualPrice - $rent;
if ($rtimeRangelevel > $ptimeRangelevel) {
$cost = $ActualPrice;
}
}
}
}
return $cost;
}
// clear checout cache
add_filter('woocommerce_checkout_get_value','__return_empty_string', 1, 1);

Related

2nd product on cart -50% based on category

I need create function in WooCommerce - 50% discount to 2nd product, if 2nd product is from category 'odziez' slug. Can anyone help me? This code not work:
<?php
add_action('woocommerce_cart_calculate_fees', 'ts_add_custom_discount', 10, 1 );
function ts_add_custom_discount( $wc_cart ){
$discount = 0;
$product_ids = array();
$in_cart = false;
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product = $cart_item['data'];
if ( has_term( 'get2', 'product_cat', $cart_product->get_id() ) ) {
$in_cart = true;
}else {
$product_ids[] = $cart_product->get_id();
}
}
if( $in_cart ) {
$count_ids = count($product_ids);
if( $count_ids >= 1 ) {
foreach( $product_ids as $id ) {
$product = wc_get_product( $id );
$price = $product->get_price();
$discount -= ($price * 50) /100; //apply 50% discount on the other product
}
}
}
if( $discount != 0 ){
$wc_cart->add_fee( 'Discount', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
Here I apply discount to less than or equal to half the amount of products. Discount only if a product is of category odziez.
add_action('woocommerce_cart_calculate_fees', 'ts_add_custom_discount', 10, 1 );
function ts_add_custom_discount( $wc_cart ){
$discount = 0;
$product_ids_with_price = array();
$product_ids = array();
$in_cart = false;
$total_odziez = 0;
$total_discounted = 0;
// count nr of odziez
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product = $cart_item['data'];
if ( has_term( 'odziez', 'product_cat', $cart_product->get_id() ) ) {
$total_odziez += $cart_item['quantity'];
}
}
foreach ( $wc_cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_product = $cart_item['data'];
$prod_id = $cart_product->get_id();
$_product = wc_get_product( $prod_id );
$price = $_product->get_price();
if ( has_term( 'odziez', 'product_cat', $prod_id ) ) {
$product_ids_with_price[$cart_product->get_id()] = $price;
}
}
asort($product_ids_with_price); // sort by price, so we get cheapest on top
foreach ( $product_ids_with_price as $prod_id => $prod_price ) {
if ($total_discounted < floor($total_odziez / 2)) { // Starting from the cheapest, add products for discounting until you have done half of all odziez products
$total_discounted++;
$product_ids[] = $prod_price;
$in_cart = true;
}
}
if( $in_cart ) {
$count_ids = count($product_ids);
if( $count_ids >= 1 ) {
foreach( $product_ids as $id => $price ) {
// $product = wc_get_product( $id );
// $price = $product->get_price();
$discount -= ($price * 50) /100; //apply 50% discount on the other product
}
}
}
if( $discount != 0 ){
$wc_cart->add_fee( 'Discount', $discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
}
Update
Changed it so it discounts every 2nd item of category odziez.
Update
I added that the cheapest products get discounted over the more expensive ones.

How to echo a php code using ob_start in another function?

I've tried to copy my php code from foreach loop using ob start but failed. Does anyone knows how to do this? I wanted to add my php code in another function like below.
foreach($kekei as $good => $goodness) {
ob_start();
$GLOBALS['myfirstbowanstart'] .= "if ( $packing_fee === 'strtolower(".$goodness['shipping_code'].")' ) {
$label = __('Shipping fee');
$cost = ".$goodness['shipping_fee'].";
}"; // put here your recursive function name
ob_get_clean();
}
// Add a custom dynamic packaging fee
add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 );
function add_packaging_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
//$domain = "woocommerce";
$packing_fee = WC()->session->get( 'the_chosen_one' ); // Dynamic packing fee
echo $GLOBALS['myfirstbowanstart'];
/*
if ( $packing_fee === 'gzeatp1' ) {
$label = __("Shipping fee");
$cost = 3.00;
} elseif ( $packing_fee === 'box' ) {
$label = __("Shipping fee");
$cost = 9.00;
}
*/
if ( isset($cost) )
$cart->add_fee( $label, $cost );
}
<?php
$GLOBALS = array("results"=>array(), "tests" => array("test1", "test2", "test3"));
$label = $cost = "";
$packing_fees = array("gzeatp1" => "3.00", "box" => "9.00", "cotton" => "12.00");
$packing_fee = "cotton"; //WC()->session->get( 'the_chosen_one' );
$kekei = array(
"first_good" => array("param1" => "value1", "shipping_code" => "gzeatp1"),
"second_good"=> array("param2" => "value2", "shipping_code" => "box"),
"third_good" => array("param3" => "value3", "shipping_code" => "cotton"),
);
$callback =
function ($shipping_code, $packing_fee) use ($cost, &$packing_fees)
{
if($packing_fee === strtolower($shipping_code)) {
$label = 'Shipping fee';
$cost = $packing_fees[$shipping_code];
$GLOBALS["results"] = array("label" => $label, "cost"=> $cost);
}
};
foreach($kekei as $good => $goodness) {
$callback($goodness['shipping_code'], $packing_fee) ;
}
// Add a custom dynamic packaging fee
//add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 );
function add_packaging_fee( $cart = "" ) {
//Disabled for testing
#if ( is_admin() && ! defined( 'DOING_AJAX' ) )
# return;
//$domain = "woocommerce";
//$packing_fee = WC()->session->get( 'the_chosen_one' ); // Dynamic packing fee
// If $label and $cost are global variables, comment out next 2 lines.
$label = $GLOBALS["results"]["label"];
$cost = $GLOBALS["results"]["cost"];
/*
if ( $packing_fee === 'gzeatp1' ) {
$label = __("Shipping fee");
$cost = 3.00;
} elseif ( $packing_fee === 'box' ) {
$label = __("Shipping fee");
$cost = 9.00;
}
*/
echo json_encode($GLOBALS);
//if ( isset($cost) )
//$cart->add_fee( $label, $cost );
}
add_packaging_fee("test");
This is the modified code merged with yours, let me know if it works,
//Added this block
$packing_fees = array("gzeatp1" => "3.00", "box" => "9.00", "cotton" => "12.00"); //This is for testing purposes
$packing_fee = WC()->session->get( 'the_chosen_one' ); // make this a global variable
$callback =
function ($shipping_code, $packing_fee) use ($cost, &$packing_fees)
{
if($packing_fee === strtolower($shipping_code)) {
$label = __('Shipping fee');
$cost = $packing_fees[$shipping_code];
$GLOBALS["myfirstbowanstart"] = array("label" => $label, "cost"=> $cost);
}
};
foreach($kekei as $good => $goodness) {
$callback($goodness['shipping_code'], $packing_fee) ;
}
/* //Removed this block
foreach($kekei as $good => $goodness) {
ob_start();
$GLOBALS['myfirstbowanstart'] .= "if ( $packing_fee === 'strtolower(".$goodness['shipping_code'].")' ) {
$label = __('Shipping fee');
$cost = ".$goodness['shipping_code'].";
}"; // put here your recursive function name
ob_get_clean();
}
*/
// Add a custom dynamic packaging fee
add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 );
function add_packaging_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
//$domain = "woocommerce";
$packing_fee = WC()->session->get( 'the_chosen_one' ); // Dynamic packing fee
//changed this line
//echo $GLOBALS['myfirstbowanstart'];
$label = $GLOBALS['myfirstbowanstart']['label'];
$cost = $GLOBALS['myfirstbowanstart']['cost'];
/*
if ( $packing_fee === 'gzeatp1' ) {
$label = __("Shipping fee");
$cost = 3.00;
} elseif ( $packing_fee === 'box' ) {
$label = __("Shipping fee");
$cost = 9.00;
}
*/
if ( isset($cost) )
$cart->add_fee( $label, $cost );
}

Symfony 4 Match Against sort by relevanece

I want to sort by revelance that mean if i have in db:
FooBa
FooBar
FooB
Foo
and i want to type foo it will be sorted:
Foo
FooB
FooBa
FooBar
public function findBySearchQueryPagin2(string $rawQuery, int $limit = 999, string $sort = "DESC", string $sortBy = "relevance", int $page = 1): pagerfanta
{
$query = $this->sanitizeSearchQuery($rawQuery);
$sort = $this->sanitizeSearchQuery($sort);
$sortBy = $this->sanitizeSearchQuery($sortBy);
$limit = $this->sanitizeSearchQuery($limit);
$page = $this->sanitizeSearchQuery($page);
if(($sort != 'ASC')&&($sort != 'DESC')) $sort = 'DESC';
if(($sortBy != 'date')&&($sortBy != 'name')&&($sortBy != 'relevance')){
$sortBy = null;
} else {
if($sortBy=="name") $sortBy = "primarytitle";
if($sortBy=="date") $sortBy = "startyear";
if($sortBy=="relevance") $sortBy = "relevance";
}
$queryBuilder = $this->createQueryBuilder('p')
->andWhere("MATCH_AGAINST (p.primarytitle, :searchTerms) > 1")
->setParameter('searchTerms', $query)
->setMaxResults($limit);
var_dump($query);
if($sortBy !== "relevance"){
$queryBuilder
->orderBy('p.' . $sortBy, $sort);
}
return $this->createPaginator($queryBuilder->getQuery(), $page);
}

WooCommerce Currency Symbol

I am recently working with WooCommerce WordPress project for my client and I am editing a plugin for WooCommerce WordPress. I am trying to display the product price to include the currency code use this function
* #param mixed $item
* #param bool $inc_tax (default: false).
* #param bool $round (default: true).
* #return float
*/
public function get_item_total( $item, $inc_tax = false, $round = true ) {
$qty = ( ! empty( $item['qty'] ) ) ? $item['qty'] : 1;
if ( $inc_tax ) {
$price = ( $item['line_total'] + $item['line_tax'] ) / max( 1, $qty );
} else {
$price = $item['line_total'] / max( 1, $qty );
}
$price = '<span class="price">' . $round ? round( $price, wc_get_price_decimals() ) . '</span>' : '<span class="price">' . $price . '</span>' ;
return apply_filters( 'woocommerce_order_amount_item_total', $price, $this, $item, $inc_tax, $round );
}
But it spits out a number like 55 with out the currency symbol. is there anyway get the number with currency symbol like $55 ?
Thank you for all your help
ty rgdesign
This was the fix it works now
public function get_item_total( $item, $inc_tax = false, $round = true ) {
$qty = ( ! empty( $item['qty'] ) ) ? $item['qty'] : 1;
if ( $inc_tax ) {
$price = ( $item['line_total'] + $item['line_tax'] ) / max( 1, $qty );
} else {
$price = $item['line_total'] / max( 1, $qty );
}
$currency_symbol = get_woocommerce_currency_symbol();
$price = $round ? round($price, wc_get_price_decimals() ): $price;
$price = '<span class="price">' .$currency_symbol . $price .'</span>';
return apply_filters( 'woocommerce_order_amount_item_total',$price, $this, $item, $inc_tax, $round );
}
I found it to be very easy. Just insert the following code block to functions.php file under theme folder.
//Change the symbol of an existing currency
add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);
switch( $currency ) {
case 'USD': $currency_symbol = 'USD$'; break;
}
return $currency_symbol;
}

Drupal Upgrade:: Need to rewrite pagerquery to version 7

I need to rewrite pagerquery, i have tried out several options adding tags, extend(PagerDefault) but nothing worked for me:
Please help.
My version 6 code is:
$sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n '.$sort_join.' WHERE n.uid = %d AND n.type = "case" AND n.status = 1 ORDER BY '. $order;
$sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n WHERE n.uid = %d AND n.type = "case" AND n.status = 1';
$args = array('uid' => $user->uid);
$sql = db_rewrite_sql($sql);
$sql_count = db_rewrite_sql($sql_count);
if ($pager) {
$result = pager_query($sql, variable_get('default_nodes_main', 10), 0, $sql_count, $args);
dsm($result);
}
else {
$result = db_query_range($sql, $args, 0, variable_get('feed_default_items', 10));
}
$num_rows = FALSE;
while ($node = db_fetch_object($result)) {
$output .= node_view(node_load($node->nid), 1);
$num_rows = TRUE;
}
Without knowing the name of your join table this isn't complete, but should get you started:
$query = db_select('node', 'n')
->fields('n', array('nid', 'sticky', 'title', 'created'))
->condition('n.uid', $user->uid)
->condition('n.type', 'case')
->condition('n.status', 1)
->extend('PagerDefault')
->limit(variable_get('default_nodes_main', 10))
->addTag('node_access')
->orderBy('col_name');
$query->join('table_to_join', 'table_alias', 'table_alias.nid = n.nid');
foreach ($query->execute() as $row) {
// Do what you need to
}
if ($vidw == 'my_cases' or $vidw == 'my') { // including private
switch ($sort_by) {
case 'rated':
$order = 'n.sticky DESC, vc.value DESC';
$sort_join = 'LEFT OUTER JOIN {votingapi_cache} vc ON n.nid = vc.content_id AND vc.content_type = "node" AND vc.function = "average"';
break;
case 'discussed':
$order = 'n.sticky DESC, nc.comment_count DESC';
$sort_join = 'LEFT OUTER JOIN {node_comment_statistics} nc ON n.nid = nc.nid';
break;
case 'viewed':
$order = 'n.sticky DESC, nc.totalcount DESC';
$sort_join = 'LEFT OUTER JOIN {node_counter} nc ON n.nid = nc.nid';
break;
case 'recent':
default:
$order = 'n.sticky DESC, n.created DESC';
$sort_join = '';
break;
}
// from taxonomy_select_nodes
$sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n '.$sort_join.' WHERE n.uid = %d AND n.type = "case" AND n.status = 1 ORDER BY '. $order;
$sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n WHERE n.uid = %d AND n.type = "case" AND n.status = 1';
$args = array('uid' => $user->uid);
$sql = db_rewrite_sql($sql);
$sql_count = db_rewrite_sql($sql_count);
if ($pager) {
$result = pager_query($sql, variable_get('default_nodes_main', 10), 0, $sql_count, $args);
}
else {
$result = db_query_range($sql, $args, 0, variable_get('feed_default_items', 10));
}
// $output .= taxonomy_render_nodes($result);
$num_rows = FALSE;
while ($node = db_fetch_object($result)) {
$output .= node_view(node_load($node->nid), 1);
$num_rows = TRUE;dsm($output);
}
if ($num_rows) {
$output .= theme('pager', NULL, variable_get('default_nodes_main', 10), 0);
}
else {
$output .= '<p>'. t('There are currently no visible cases in this category.') .'</p>';
}
}
In above drupal 6 code, i have updated the query which gives me result but node_view() and theme() does not work.

Resources