post_meta get_the_ID Not working in wordpress - wordpress

The commands get_post_meta(get_the_ID(), 'add_price', true); are not working at this function of my wordpress site:
function misha_recalculate_price( $cart_object ) {
var_dump(get_post_type($post_ID));
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach ( $cart_object->get_cart() as $hash => $value ) {
$nowprice = $value['data']->get_price();
$addprice = get_post_meta(get_the_ID(), 'add_price', true);
$newprice = $nowprice+$addprice ;
$value['data']->set_price( $newprice );
}
}
add_action( 'woocommerce_before_calculate_totals', 'misha_recalculate_price' );

can you give it a try this way?
function misha_recalculate_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
foreach ( $cart_object->get_cart() as $hash => $value ) {
$nowprice = $value['data']->get_price();
$addprice = get_post_meta($value['data']->get_id(), 'add_price', true);
$newprice = $nowprice + $addprice;
$value['data']->set_price( $newprice );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'misha_recalculate_price', 10, 1 );

function misha_recalculate_price( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
foreach ( $cart_object->get_cart() as $hash => $value ) {
$nowprice = $value['data']->get_price();
$addprice = get_post_meta($value['data']->get_id(), 'cost_price', true);
$newprice = $nowprice+$addprice ;
$value['data']->set_price( $newprice );
}
}
add_action( 'woocommerce_before_calculate_totals', 'misha_recalculate_price', 10, 1 );

Related

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 );
}

Show price next to the variations in WooCommerce

I am using the below code to display price next to the variations in WooCommerce. It works great if more than 2 variations but if only 2 variations it displays only the first variations price for both variations.
Any help with this would be great.
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
if ( is_product() ) {
if ( $product instanceof WC_Product && $product->is_type( 'variable' ) ) {
foreach ( $product->get_available_variations() as $variation ) {
//$product_variation_id = $variation['variation_id'];
foreach ( $variation['attributes'] as $variation_attribute_name => $variation_attribute_value ) {
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE slug = '$variation_attribute_value'" );
if ( $term != $variation_attribute_value && $variation_attribute_value != $result[0] ) continue;
$product_price = wc_price( $variation['display_price'] );
$product_price = strip_tags( $product_price );
return $term . ' - (' . $product_price . ')';
}
}
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
This code is tested and works with multiple dropdowns and multiple attributes and product specific attributes like, attribute1 | attribute2 | attribute3.
// Add the prices next to the variations in WooCommerce
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_names' );
function display_price_in_variation_option_names( $term_name ) {
global $wpdb, $product;
if ( is_product() && $product instanceof WC_Product && $product->is_type( 'variable' ) ) {
foreach ( $product->get_available_variations() as $variation ) {
foreach ( $variation['attributes'] as $variation_attribute_name => $variation_attribute_value ) {
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE slug = '$variation_attribute_value'" );
$taxonomy = str_replace( 'attribute_', '', $variation_attribute_name );
$term = get_term_by( 'slug', $variation_attribute_value, $taxonomy );
if ( $term_name == $variation_attribute_value ) {
$product_price = wc_price( $variation['display_price'] );
$product_price = strip_tags( $product_price );
return $term_name . ' - (' . $product_price . ')';
} else if( is_object($term) && $term->name == $term_name ) {
$product_price = wc_price( $variation['display_price'] );
$product_price = strip_tags( $product_price );
return $term_name . ' - (' . $product_price . ')';
}
}
}
}
return $term_name;
}

How can I change the Total of price existing in WooCommerce

How Can I change the Total price of the cart using hook.
I have tried many hooks without result.
i'm probably arrived to find the result .
This is what I have tried.
add_action('woocommerce_checkout_process', 'wh_getCartItemBeforePayment', 10);
function wh_getCartItemBeforePayment(){
if($_POST['percent']){
if($_POST['percent']==1){
/*WC()->cart->total*0.25;
WC()->cart->calculate_totals();
woocommerce_cart_totals();*/
/*
add_action('woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$percentage = 0.01;
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
}
throw new Exception( __( WC()->cart->total ) );*/
//$items = WC()->cart->get_cart();
$cupom_value=-1;
foreach ($items as $item => $values)
{
$_product = $values['data']->post;
$product_title = $_product->post_title;
$qty = $values['quantity'];
$price = get_post_meta($values['product_id'], '_price', true);
$post_id = $value['product_id'];
$regular_price = get_post_meta( $post_id, '_regular_price', true);
$sale_price = get_post_meta( $post_id, '_sale_price', true);
$cupom_value = ($regular_price - $sale_price) *0.25;
$price = $cupom_value;
$value['data']->price = $price;
}
//$price=3*0.25;
wc_add_notice($cupom_value, 'error' );
}}}
add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );
function action_cart_calculate_totals( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( !WC()->cart->is_empty() ):
$cart_object->cart_contents_total += 10; // add 10 to cart total
endif;
}

dont allow PO BOX shipping woocommerce not working

add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');
function deny_pobox_postcode( $posted ) {
global $woocommerce;
$address = ( isset( $posted['shipping_address_1'] ) ) ? $posted['shipping_address_1'] : $posted['billing_address_1'];
$postcode = ( isset( $posted['shipping_postcode'] ) ) ? $posted['shipping_postcode'] : $posted['billing_postcode'];
$replace = array(" ", ".", ",");
$address = strtolower( str_replace( $replace, '', $address ) );
$postcode = strtolower( str_replace( $replace, '', $postcode ) );
if ( strstr( $address, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
$woocommerce->add_error( "Sorry, we don't ship to PO BOX addresses." );
}
}
i am getting:
fatal error :call to undefined add_error
when i am pasting on my function .php
add_error() has been renamed to wc_add_notice():
$woocommerce->wc_add_notice( "Sorry, we don't ship to PO BOX addresses." );
add_action('woocommerce_after_checkout_validation', 'deny_pobox_postcode');
function deny_pobox_postcode( $posted ) {
global $woocommerce;
$address = ( isset( $posted['shipping_address_1'] ) ) ?
$posted['shipping_address_1'] : $posted['billing_address_1'];
$postcode = ( isset( $posted['shipping_postcode'] ) ) ?
$posted['shipping_postcode'] : $posted['billing_postcode'];
$replace = array(" ", ".", ",");
$address = strtolower( str_replace( $replace, '', $address ) );
$postcode = strtolower( str_replace( $replace, '', $postcode ) );
if ( strstr( $address, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
$notice = sprintf( __( '%1$sSorry, we dont ship to PO BOX addresses..' , 'error' ) , '<strong>' , '</strong>' );
if ( version_compare( WC_VERSION, '2.3', '<' ) ) {
$woocommerce->add_error( $notice );
} else {
wc_add_notice( $notice, 'error' );
}
}
}
<?php
add_filter('woocommerce_package_rates',
'shomaris_hide_fedex_for_po_box_shipment',
10, 2);
function shomaris_hide_fedex_for_po_box_shipment($available_shipping_methods,
$package){
$shipping_method_to_hide = 'flat_rate:4';
// $shipping_method_to_hides = 'flat_rate:5';
global $woocommerce;
$address = ( !empty( $woocommerce->customer->get_shipping_address_1() ) ) ?
$woocommerce->customer->get_shipping_address_1() : $woocommerce->customer-
>get_billing_address_1();
$postcode = ( !empty( $woocommerce->customer->get_shipping_postcode() ) ) ?
$woocommerce->customer->get_shipping_postcode() : $woocommerce->customer-
>get_billing_postcode();
$replace = array(" ", ".", ",");
$address2 = strtolower( str_replace( $replace, '', $address ) );
if ( strstr( $address2, 'pobox' ) ) {
foreach ($available_shipping_methods as $shipping_method => $value) {
if( strpos( $shipping_method, $shipping_method_to_hide,
$shipping_method_to_hides ) !== false ) {
unset($available_shipping_methods[$shipping_method]);
}
}
}
return $available_shipping_methods;
}
?>

How to select single category in menu if post have two categories?

My website's post have one, two, three etc categories depends on articles. My menu is made of categories. when i select post (open whole article) it shows post category in menu.
Problem : when i select such article who have two category that time menu shows two selection of menus. how can i show only one category (first category)?
In above image you can see that when i select some post who have two category that time two menu selected.
Shall do changes in function.php, nav-menu-template.php or anywhere else....
foreach ( (array) $menu_items as $key => $menu_item ) {
$menu_items[$key]->current = false;
$classes = (array) $menu_item->classes;
$classes[] = 'menu-item';
$classes[] = 'menu-item-type-' . $menu_item->type;
$classes[] = 'menu-item-object-' . $menu_item->object;
// if the menu item corresponds to a taxonomy term for the currently-queried non-hierarchical post object
if ( $wp_query->is_singular && 'taxonomy' == $menu_item->type && in_array( $menu_item->object_id, $possible_object_parents ) ) {
$active_parent_object_ids[] = (int) $menu_item->object_id;
$active_parent_item_ids[] = (int) $menu_item->db_id;
$active_object = $queried_object->post_type;
// if the menu item corresponds to the currently-queried post or taxonomy object
} elseif (
$menu_item->object_id == $queried_object_id &&
(
( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && $wp_query->is_home && $home_page_id == $menu_item->object_id ) ||
( 'post_type' == $menu_item->type && $wp_query->is_singular ) ||
( 'taxonomy' == $menu_item->type && ( $wp_query->is_category || $wp_query->is_tag || $wp_query->is_tax ) && $queried_object->taxonomy == $menu_item->object )
)
) {
$classes[] = 'current-menu-item';
$menu_items[$key]->current = true;
$_anc_id = (int) $menu_item->db_id;
while(
( $_anc_id = get_post_meta( $_anc_id, '_menu_item_menu_item_parent', true ) ) &&
! in_array( $_anc_id, $active_ancestor_item_ids )
) {
$active_ancestor_item_ids[] = $_anc_id;
}
if ( 'post_type' == $menu_item->type && 'page' == $menu_item->object ) {
// Back compat classes for pages to match wp_page_menu()
$classes[] = 'page_item';
$classes[] = 'page-item-' . $menu_item->object_id;
$classes[] = 'current_page_item';
}
$active_parent_item_ids[] = (int) $menu_item->menu_item_parent;
$active_parent_object_ids[] = (int) $menu_item->post_parent;
$active_object = $menu_item->object;
// if the menu item corresponds to the currently-requested URL
} elseif ( 'custom' == $menu_item->object ) {
$_root_relative_current = untrailingslashit( $_SERVER['REQUEST_URI'] );
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_root_relative_current );
$raw_item_url = strpos( $menu_item->url, '#' ) ? substr( $menu_item->url, 0, strpos( $menu_item->url, '#' ) ) : $menu_item->url;
$item_url = untrailingslashit( $raw_item_url );
$_indexless_current = untrailingslashit( preg_replace( '/' . preg_quote( $wp_rewrite->index, '/' ) . '$/', '', $current_url ) );
if ( $raw_item_url && in_array( $item_url, array( $current_url, $_indexless_current, $_root_relative_current ) ) ) {
$classes[] = 'current-menu-item';
$menu_items[$key]->current = true;
$_anc_id = (int) $menu_item->db_id;
while(
( $_anc_id = get_post_meta( $_anc_id, '_menu_item_menu_item_parent', true ) ) &&
! in_array( $_anc_id, $active_ancestor_item_ids )
) {
$active_ancestor_item_ids[] = $_anc_id;
}
if ( in_array( home_url(), array( untrailingslashit( $current_url ), untrailingslashit( $_indexless_current ) ) ) ) {
// Back compat for home link to match wp_page_menu()
$classes[] = 'current_page_item';
}
$active_parent_item_ids[] = (int) $menu_item->menu_item_parent;
$active_parent_object_ids[] = (int) $menu_item->post_parent;
$active_object = $menu_item->object;
// give front page item current-menu-item class when extra query arguments involved
} elseif ( $item_url == $front_page_url && is_front_page() ) {
//$classes[] = 'current-menu-item';
}
if ( untrailingslashit($item_url) == home_url() )
$classes[] = 'menu-item-home';
}
// back-compat with wp_page_menu: add "current_page_parent" to static home page link for any non-page query
if ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && empty( $wp_query->is_page ) && $home_page_id == $menu_item->object_id )
$classes[] = 'current_page_parent';
$menu_items[$key]->classes = array_unique( $classes );
}
`
Yes, Finally i had done it. I done changes in nav-menu-template.php.
I created one variable and initialized with 1 above
foreach ( (array) $menu_items as $key => $parent_item ) {
this code.
and add conditional code
if($repetation == '1'){//to stop second selection of menu
$classes[] = 'current-menu-parent';
$menu_items[$key]->current_item_parent = true;
$repetation++;
}
else{
//echo $repetation;
}
inbetween
if ( in_array( $parent_item->db_id, $active_parent_item_ids ) ) {
...}
this.
whole code look like
$repetation = '1';
// set parent's class
foreach ( (array) $menu_items as $key => $parent_item ) {
$classes = (array) $parent_item->classes;
$menu_items[$key]->current_item_ancestor = false;
$menu_items[$key]->current_item_parent = false;
if (
isset( $parent_item->type ) &&
(
// ancestral post object
(
'post_type' == $parent_item->type &&
! empty( $queried_object->post_type ) &&
is_post_type_hierarchical( $queried_object->post_type ) &&
in_array( $parent_item->object_id, $queried_object->ancestors ) &&
$parent_item->object != $queried_object->ID
) ||
// ancestral term
(
'taxonomy' == $parent_item->type &&
isset( $possible_taxonomy_ancestors[ $parent_item->object ] ) &&
in_array( $parent_item->object_id, $possible_taxonomy_ancestors[ $parent_item->object ] ) &&
(
! isset( $queried_object->term_id ) ||
$parent_item->object_id != $queried_object->term_id
)
)
)
) {
$classes[] = empty( $queried_object->taxonomy ) ? 'current-' . $queried_object->post_type . '-ancestor' : 'current-' . $queried_object->taxonomy . '-ancestor';
}
if ( in_array( intval( $parent_item->db_id ), $active_ancestor_item_ids ) ) {
$classes[] = 'current-menu-ancestor';
$menu_items[$key]->current_item_ancestor = true;
}
if ( in_array( $parent_item->db_id, $active_parent_item_ids ) ) {
if($repetation == '1'){//to stop second selection of menu
$classes[] = 'current-menu-parent';
$menu_items[$key]->current_item_parent = true;
$repetation++;
}
else{
//echo $repetation;
}
}
if ( in_array( $parent_item->object_id, $active_parent_object_ids ) )
$classes[] = 'current-' . $active_object . '-parent';
if ( 'post_type' == $parent_item->type && 'page' == $parent_item->object ) {
// Back compat classes for pages to match wp_page_menu()
if ( in_array('current-menu-parent', $classes) )
$classes[] = 'current_page_parent';
if ( in_array('current-menu-ancestor', $classes) )
$classes[] = 'current_page_ancestor';
}
$menu_items[$key]->classes = array_unique( $classes );
}

Resources