Replace meta value - php

I searched for a while and I tried several options but I didn't find any solution. So, i have the following string that gets the status of a costum field to export to other websites.
<category><![CDATA[<?php listingpress_listing_status(); ?>]]></category>
It outputs something like this:
<category><![CDATA[For sale]]></category>
And what i need is to turn this value into a number.
Ex:
For sale » 100
For Rent » 110
Sold » 120
This is the original function:
if ( ! function_exists( 'listingpress_listing_status' ) ) :
/**
* Prints listing status
*
* #since ListingPress 1.0
*
* #uses listingpress_get_listing_status() To get listing status
*/
function listingpress_listing_status() {
echo listingpress_get_listing_status( 'name' );
}
endif; // listingpress_listing_status
if ( ! function_exists( 'listingpress_get_listing_status' ) ) :
function listingpress_get_listing_status( $fields = 'name' ) {
global $meta_prefix, $post;
if ( of_get_option( 'enable_listing_status', true ) ) {
$status = get_post_meta( $post->ID, $meta_prefix . 'status', true );
if ( $status == 'sold' ) {
if ( $fields == 'name' )
return __( 'Sold', 'listingpress' );
elseif ( $fields == 'slug' )
return 'sold';
} elseif ( $status == 'for-sale' ) {
if ( $fields == 'name' )
return __( 'For sale', 'listingpress' );
elseif ( $fields == 'slug' )
return 'for-sale';
} elseif ( $status == 'for-rent' ) {
if ( $fields == 'name' )
return __( 'For rent', 'listingpress' );
elseif ( $fields == 'slug' )
return 'for-rent';
}
} else {
return 'no-status';
}
}
endif; // listingpress_get_listing_status
Could someone please help me with this?
Thank you in advance.

So basically you can do something as mentioned below:
<?php
$listing_status = '';
if(listingpress_listing_status() == 'For sale') {
$listing_status = 100;
} elseif(listingpress_listing_status() == 'For rent') {
$listing_status = 110;
} elseif(listingpress_listing_status() == 'For rent') {
$listing_status = 120;
} else {
$listing_status = listingpress_listing_status();
}
?>
<category><![CDATA[<?php echo $listing_status; ?>]]></category>
A word of advice, share the problem directly with code from the beginning so that you can get help quicker.

Related

wp_send_json doesn't work after do_action on Wordpress

I need to interact with a third party plugin to send SMS. The plugin is Bookly, which is for making appointments. I edited the Ajax.php that Bookly uses for saving the appointment. I've sent the SMS succesfully on Ajax.php. However, I want to code an external plugin to make the process controllable on admin panel.
I use a custom hook named "bookly_appointment_saved" and send an array with that. And in my new plugin I catch the hook succesfully. The SMS is always sent but the Ajax.php of Bookly doesn't send the response to the frontend. It keeps showing the page as loading.
Please see the codes below and help.
Ajax.php (Bookly) - Only related method is included.
/**
* Save cart appointments.
*/
public static function saveAppointment()
{
$userData = new Lib\UserBookingData( self::parameter( 'form_id' ) );
if ( $userData->load() ) {
$failed_cart_key = $userData->cart->getFailedKey();
if ( $failed_cart_key === null ) {
$cart_info = $userData->cart->getInfo();
$is_payment_disabled = Lib\Config::paymentStepDisabled();
$skip_payment = BookingProxy\CustomerGroups::getSkipPayment( $userData->getCustomer() );
$gateways = self::getGateways( $userData, clone $cart_info );
if ( $is_payment_disabled || isset( $gateways['local'] ) || $cart_info->getPayNow() <= 0 || $skip_payment ) {
// Handle coupon.
$coupon = $userData->getCoupon();
if ( $coupon ) {
$coupon->claim()->save();
}
// Handle payment.
$payment = null;
if ( ! $is_payment_disabled && ! $skip_payment ) {
if ( $cart_info->getTotal() <= 0 ) {
if ( $cart_info->withDiscount() ) {
$payment = new Lib\Entities\Payment();
$payment
->setType( Lib\Entities\Payment::TYPE_FREE )
->setStatus( Lib\Entities\Payment::STATUS_COMPLETED )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( 0 )
->setPaid( 0 )
->save();
}
} else {
$payment = new Lib\Entities\Payment();
$status = Lib\Entities\Payment::STATUS_PENDING;
$type = Lib\Entities\Payment::TYPE_LOCAL;
$paid = 0;
foreach ( $gateways as $gateway => $data ) {
if ( $data['pay'] == 0 ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$type = Lib\Entities\Payment::TYPE_FREE;
$cart_info->setGateway( $gateway );
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
break;
}
}
if ( $status !== Lib\Entities\Payment::STATUS_COMPLETED ) {
$gift_card = $userData->getGiftCard();
if ( $gift_card ) {
$type = Lib\Entities\Payment::TYPE_CLOUD_GIFT;
$cart_info->setGateway( $type );
if ( $gift_card->getBalance() >= $cart_info->getPayNow() ) {
$status = Lib\Entities\Payment::STATUS_COMPLETED;
$paid = $cart_info->getPayNow();
$gift_card->charge( $paid )->save();
$payment->setGatewayPriceCorrection( $cart_info->getPriceCorrection() );
}
}
}
$payment
->setType( $type )
->setStatus( $status )
->setPaidType( Lib\Entities\Payment::PAY_IN_FULL )
->setTotal( $cart_info->getTotal() )
->setTax( $cart_info->getTotalTax() )
->setPaid( $paid )
->save();
}
}
// Save cart.
$order = $userData->save( $payment );
if ( $payment !== null ) {
$payment->setDetailsFromOrder( $order, $cart_info )->save();
}
// Send notifications.
Lib\Notifications\Cart\Sender::send( $order );
$response = array(
'success' => true,
);
} else {
$response = array(
'success' => false,
'error' => Errors::PAY_LOCALLY_NOT_AVAILABLE,
);
}
} else {
$response = array(
'success' => false,
'failed_cart_key' => $failed_cart_key,
'error' => Errors::CART_ITEM_NOT_AVAILABLE,
);
}
//Custom hook
$user_appointed=$userData->getData();
do_action('bookly_appointment_saved',
$appointment=[
'date'=>date("d/m/Y", strtotime($user_appointed['slots'][0][2]) ),
'time'=>date("H:i", strtotime($user_appointed['slots'][0][2]) ),
'full_name'=>$user_appointed['full_name']=''?$user_appointed['first_name'].' '.$user_appointed['last_name']:$user_appointed['full_name'],
'service_name'=>$userData->cart->getItemsTitle(),
]
);
// end of hook
$userData->sessionSave();
wp_send_json( $response );
}
Errors::sendSessionError();
}
custom-sms-sender-plugin.php (My plugin)
add_action('bookly_appointment_saved','send_sms');
function send_sms($appointment){
$phone = "66666666666";
$message="New appointment - ".$appointment['full_name']." Service: ".$appointment['service_name']." Date: ".$appointment['date']." Time:".$appointment['time'];
$message = urlencode($message);
$url= "//request url with parameters";
$request = wp_remote_get($url);
if ($request['body'] !=30 || $request['body'] !=20 || $request['body'] !=40 || $request['body'] !=50 || $request['body'] != 51 || $request['body'] != 70 || $request['body'] != 85) {
write_log("SENT - SMS Code : ".explode(" ",$request['body'])[1]);
} else {
write_log("ERROR - Code : ".$request['body']);
}
}
I've solved the problem. It is caused by the "write_log" commands as the command doesn't exist. After changing the log method, it worked like a charm. Thanks for all comments.

Woocommerce custom add to cart with unique id

I am not that proficient at coding so please bear with me.
I have this custom add to cart code:
public static function add_to_cart( $params, $uid ) {
$data = self::get_calc_data($uid);
foreach ($data as $calc_id => $calc_data) {
$product_id = isset($calc_data['woo_info']['product_id']) ? $calc_data['woo_info']['product_id'] : null;
if ( $product_id && intval($product_id) === intval($params['woo_info']['product_id']) ) {
$meta = [
'product_id' => $product_id,
'item_name' => isset($calc_data['item_name']) ? $calc_data['item_name'] : '',
];
if(!empty($calc_data['descriptions']) && is_array($calc_data['descriptions'])) {
foreach ($calc_data['descriptions'] as $calc_item) {
if ( $calc_item['hidden'] === true ){
continue;
}
if ( strpos($calc_item['alias'], 'datePicker_field_id_') !== false ) {
$val = $calc_item['converted'] ? ' ('. $calc_item['converted'] . ') ' . $calc_item['value'] : $calc_item['value'];
}else{
$labels = isset($calc_item['extra']) ? $calc_item['extra']: '';
if ( (strpos($calc_item['alias'], 'radio_field_id_') !== false
|| strpos($calc_item['alias'], 'dropDown_field_id_') !== false)
&& key_exists('options', $calc_item) ) {
$labels = CCBWooCheckout::getLabels($calc_item['options']);
}
if ( strpos($calc_item['alias'], 'multi_range_field_id_') !== false
&& key_exists('options', $calc_item) && count($calc_item['options']) > 0 ) {
$labels = key_exists('label', $calc_item['options'][0]) ?
$calc_item['options'][0]['label']: '';
}
$val = isset($labels) ? $labels . ' ' . $calc_item['converted'] : $calc_item['converted'];
}
$meta['calc_data'][$calc_item['label']] = $val;
}
}
/** add totals data */
if( !empty($calc_data['ccb_total_and_label']) && is_array($calc_data['ccb_total_and_label']) ) {
$meta['ccb_total'] = $calc_data['ccb_total_and_label']['total'];
}
WC()->cart->add_to_cart($product_id, 1, '', array(), array('ccb_calculator' => $meta));
}
}
}
It adds simple item from a plugin into Woocommerce Cart. I am trying to add a unique ID for every added item so that I can add multiples of the same item and they would show as unique items in the cart.
I was trying to create the unique ID with
public static function add_custom_cart_item_data( $cart_item_data, $cart_item_key ) {
$cart_item_data[custom_data]['unique_key'] = md5( microtime().rand() );
return $cart_item_data;
}
and then use the $cart_item_data; changing the 'product_id' => $product_id, to 'product_id' => $cart_item_data, but sadly this doesn't seem to work. What am I doing wrong?
Really appreciate all your help!

Display SKU in Woocommerce single product page with OceanWP theme

I want to display the SKU field of each product in its signle product page. The woocommerce plugin's settings does not have that option in wordpress.
I already followed the instructions here:
https://wordpress.stackexchange.com/questions/219410/how-to-show-product-sku-on-product-page/219427#219427
I tried adding to my functions.php file this code:
add_action( 'woocommerce_single_product_summary', 'dev_designs_show_sku', 5 );
function dev_designs_show_sku(){
global $product;
echo 'SKU: ' . $product->get_sku();
}
And also tried to add this code to the theme's single product content file:
if ( 'sku' === $element ) {
woocommerce_template_single_sku();
}
file name is owp-single-product.php:
<?php
/**
* Single product template.
*
* #package OceanWP WordPress theme
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
// Get price conditional display state.
$ocean_woo_single_cond = get_theme_mod( 'ocean_woo_single_conditional', false );
// Conditional vars.
$show_woo_single = '';
$show_woo_single = ( is_user_logged_in() && $ocean_woo_single_cond === true );
/**
* Display Single Product template
*
*/
// Get elements.
$elements = oceanwp_woo_summary_elements_positioning();
// Loop through elements.
foreach ( $elements as $element ) {
do_action( 'ocean_before_single_product_' . $element );
// Title.
if ( 'title' === $element ) {
woocommerce_template_single_title();
}
// Sku.
if ( 'sku' === $element ) {
woocommerce_template_single_sku();
}
// Rating.
if ( 'rating' === $element ) {
woocommerce_template_single_rating();
}
// Price.
if ( 'price' === $element ) {
if ( false === $ocean_woo_single_cond || $show_woo_single ) {
woocommerce_template_single_price();
}
}
// Excerpt.
if ( 'excerpt' === $element ) {
woocommerce_template_single_excerpt();
}
// Quantity & Add to cart button.
if ( 'quantity-button' === $element ) {
if ( false === $ocean_woo_single_cond || $show_woo_single ) {
woocommerce_template_single_add_to_cart();
} else {
// Get Add to Cart button message display state.
$ocean_woo_single_msg = get_theme_mod( 'ocean_woo_single_cond_msg', 'yes' );
if ( 'yes' === $ocean_woo_single_msg ) {
// Get Add to Cart button replacement message.
$ocean_woo_single_msg_txt = get_theme_mod( 'ocean_woo_single_cond_msg_text' );
$ocean_woo_single_msg_txt = $ocean_woo_single_msg_txt ? $ocean_woo_single_msg_txt : esc_html__( 'Log in to view price and purchase', 'oceanwp' );
$woo_single_myaccunt_link = get_theme_mod( 'ocean_single_add_myaccount_link', false );
echo '<div class="owp-woo-single-cond-notice">';
if ( false === $woo_single_myaccunt_link ) {
echo '<span>'. $ocean_woo_single_msg_txt .'</span>';
} else {
echo '' . $ocean_woo_single_msg_txt . '';
}
echo '</div>';
}
}
}
// Meta.
if ( 'meta' === $element ) {
woocommerce_template_single_meta();
}
do_action( 'ocean_after_single_product_' . $element );
}
Did not work! What do I do?
You can try this to show the sku after product title
add_action( 'ocean_after_single_product_title', 'show_product_sku', 5 );
function show_product_sku(){
global $product;
echo 'SKU: ' . $product->get_sku();
}

Order properties should not be accessed directly - WooCommerce 3.0

I've just upgraded my local WooCommerce website to 3.0. Everything works perfectly as normal, but I've noticed with debugging turned on that I'm getting hundreds of the following notices:
[05-Apr-2017 12:25:00 UTC] PHP Notice: id was called <strong>incorrectly</strong>. Order properties should not be accessed directly. Please see Debugging in WordPress for more information. (This message was added in version 3.0.) in C:\xampp\htdocs\dev\wp-includes\functions.php on line 4137
So it looks like WooCommerce are pulling back being able to directly call order data. One example this code is being triggered by is this function in my functions.php file:
function eden_woocommerce_order_number($original, $order)
{
return 'EDN-' . str_pad($order->id, 10, 0, STR_PAD_LEFT);
}
This function simply adds "EDN" to the start of the order ID and pads it by 10 characters, but WooCommerce doesn't like how I'm calling $order - what would be the best way to rewrite such a function that 3.0 is happy with?
it says "id was called incorrectly. Order properties should not be accessed directly."
Try $order->get_id()
Maybe its helpful for others too. Here's the some stuff regarding to all the functions of directly accessed values through the magic function.
This function is from Woocommerce 3.0
if ( 'completed_date' === $key ) {
return $this->get_date_completed() ? gmdate( 'Y-m-d H:i:s', $this->get_date_completed()->getOffsetTimestamp() ) : '';
} elseif ( 'paid_date' === $key ) {
return $this->get_date_paid() ? gmdate( 'Y-m-d H:i:s', $this->get_date_paid()->getOffsetTimestamp() ) : '';
} elseif ( 'modified_date' === $key ) {
return $this->get_date_modified() ? gmdate( 'Y-m-d H:i:s', $this->get_date_modified()->getOffsetTimestamp() ) : '';
} elseif ( 'order_date' === $key ) {
return $this->get_date_created() ? gmdate( 'Y-m-d H:i:s', $this->get_date_created()->getOffsetTimestamp() ) : '';
} elseif ( 'id' === $key ) {
return $this->get_id();
} elseif ( 'post' === $key ) {
return get_post( $this->get_id() );
} elseif ( 'status' === $key ) {
return $this->get_status();
} elseif ( 'post_status' === $key ) {
return get_post_status( $this->get_id() );
} elseif ( 'customer_message' === $key || 'customer_note' === $key ) {
return $this->get_customer_note();
} elseif ( in_array( $key, array( 'user_id', 'customer_user' ) ) ) {
return $this->get_customer_id();
} elseif ( 'tax_display_cart' === $key ) {
return get_option( 'woocommerce_tax_display_cart' );
} elseif ( 'display_totals_ex_tax' === $key ) {
return 'excl' === get_option( 'woocommerce_tax_display_cart' );
} elseif ( 'display_cart_ex_tax' === $key ) {
return 'excl' === get_option( 'woocommerce_tax_display_cart' );
} elseif ( 'cart_discount' === $key ) {
return $this->get_total_discount();
} elseif ( 'cart_discount_tax' === $key ) {
return $this->get_discount_tax();
} elseif ( 'order_tax' === $key ) {
return $this->get_cart_tax();
} elseif ( 'order_shipping_tax' === $key ) {
return $this->get_shipping_tax();
} elseif ( 'order_shipping' === $key ) {
return $this->get_shipping_total();
} elseif ( 'order_total' === $key ) {
return $this->get_total();
} elseif ( 'order_type' === $key ) {
return $this->get_type();
} elseif ( 'order_currency' === $key ) {
return $this->get_currency();
} elseif ( 'order_version' === $key ) {
return $this->get_version();
} elseif ( is_callable( array( $this, "get_{$key}" ) ) ) {
return $this->{"get_{$key}"}();
} else {
return get_post_meta( $this->get_id(), '_' . $key, true );
}
You should call the woo get function. add get_ ()
For example, change:
$order->status to $order->get_status()

Can I modify this wordpress plugin function with a action/filter hook?

I need to modify 3 lines in a function created by a plugin.
Here is the original function (look for my commented section in the middle, highlighted by the asterisks):
/**
* function to modify order_items of renewal order
*
* #param array $order_items
* #param int $original_order_id
* #param int $renewal_order_id
* #param int $product_id
* #param string $new_order_role
* #return array $order_items
*/
public function sc_subscriptions_renewal_order_items( $order_items = null, $original_order_id = 0, $renewal_order_id = 0, $product_id = 0, $new_order_role = null ) {
$is_subscription_order = wcs_order_contains_subscription( $original_order_id );
if ( $is_subscription_order ) {
$return = false;
} else {
$return = true;
}
if ( $return ) {
return $order_items;
}
$pay_from_credit_of_original_order = get_option( 'pay_from_smart_coupon_of_original_order', 'yes' );
if ( $pay_from_credit_of_original_order != 'yes' ) return $order_items;
if ( $new_order_role != 'child' ) return $order_items;
if ( empty( $renewal_order_id ) || empty( $original_order_id ) ) return $order_items;
$original_order = $this->get_order( $original_order_id );
$renewal_order = $this->get_order( $renewal_order_id );
$coupon_used_in_original_order = $original_order->get_used_coupons();
$coupon_used_in_renewal_order = $renewal_order->get_used_coupons();
if ( sizeof( $coupon_used_in_original_order ) > 0 ) {
$smart_coupons_contribution = array();
foreach ( $coupon_used_in_original_order as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code );
if ( ! empty( $coupon->discount_type ) && $coupon->discount_type == 'smart_coupon' && ! empty( $coupon->amount ) && ! in_array( $coupon_code, $coupon_used_in_renewal_order, true ) ) {
$renewal_order_total = $renewal_order->get_total();
/* ************
THE BELOW 3 LINES ARE WHAT I NEED TO REMOVE
**************** */
if ( $coupon->amount < $renewal_order_total ) {
continue;
}
/* ************
THE ABOVE 3 LINES ARE WHAT I NEED TO REMOVE
**************** */
$discount = min( $renewal_order_total, $coupon->amount );
if ( $discount > 0 ) {
$new_order_total = $renewal_order_total - $discount;
update_post_meta( $renewal_order_id, '_order_total', $new_order_total );
update_post_meta( $renewal_order_id, '_order_discount', $discount );
if ( $new_order_total <= floatval(0) ) {
update_post_meta( $renewal_order_id, '_renewal_paid_by_smart_coupon', 'yes' );
}
$renewal_order->add_coupon( $coupon_code, $discount );
$smart_coupons_contribution[ $coupon_code ] = $discount;
$used_by = $renewal_order->get_user_id();
if ( ! $used_by ) {
$used_by = $renewal_order->billing_email;
}
$coupon->inc_usage_count( $used_by );
}
}
}
if ( ! empty( $smart_coupons_contribution ) ) {
update_post_meta( $renewal_order_id, 'smart_coupons_contribution', $smart_coupons_contribution );
}
}
return $order_items;
}
I want to remove the lines that I commented out in the middle of the above code:
if ( $coupon->amount < $renewal_order_total ) {
continue;
}
Is there any way to do this without editing the core plugin code? Could I write my own function to change those lines?
Thank you for any help you can provide!
If this function is hooked in with an action/filter hook then you can remove it by remove_action or remove_filter and hook in your function there.
https://codex.wordpress.org/Function_Reference/remove_action
https://codex.wordpress.org/Function_Reference/remove_filter
So check where this function gets called.

Categories