for some extra needs i had to add some extra codes in fucnctions.php i notice slowing in my site i dont know if it has connection functions.php with jquery.js ,is there a anyway to optimize it ? its ok if i remove the entering space between the lines in fucntions.php id like to make as light as i can
/**
* Adding Custom GTIN Meta Field
* Save meta data to DB
*/
// add GTIN input field
add_action('woocommerce_product_options_inventory_product_data','woocom_simple_product_gtin_field', 10, 1 );
function woocom_simple_product_gtin_field(){
global $woocommerce, $post;
$product = new WC_Product(get_the_ID());
echo '<div id="gtin_attr" class="options_group">';
//add GTIN field for simple product
woocommerce_wp_text_input(
array(
'id' => '_gtin',
'label' => __( 'GTIN', 'textdomain' ),
'placeholder' => '01234567891231',
'desc_tip' => 'true',
'description' => __( 'Enter the Global Trade Item Number (UPC,EAN,ISBN)', 'textdomain' )
)
);
echo '</div>';
}
// save simple product GTIN
add_action('woocommerce_process_product_meta','woocom_simple_product_gtin_save');
function woocom_simple_product_gtin_save($post_id){
$gtin_post = $_POST['_gtin'];
// save the gtin
if(isset($gtin_post)){
update_post_meta($post_id,'_gtin', esc_attr($gtin_post));
}
// remove if GTIN meta is empty
$gtin_data = get_post_meta($post_id,'_gtin', true);
if (empty($gtin_data)){
delete_post_meta($post_id,'_gtin', '');
}
}
add_filter( 'rank_math/snippet/rich_snippet_product_entity', function( $entity ) {
global $post;
$entity['gtin8'] = get_post_meta( $post->ID,'_gtin', true );
return $entity;
});
/*
Tracking Info to WooCommerce order
Version: 0.4
$Id: tracking-info-to-wc-order.php 5168 2020-07-15 14:48:44Z damien $
*/
// Add the metabox to allow for manual entering (or editing) of tracking information.
add_action( 'cmb2_admin_init', 'dcwd_order_metabox' );
function dcwd_order_metabox() {
$cmb = new_cmb2_box( array(
'id' => 'order_tracking_info',
'title' => 'Tracking Information',
'object_types' => array( 'shop_order', ), // Post type
'context' => 'side',
'priority' => 'high',
'show_names' => true, // Show field names on the left
) );
$cmb->add_field( array(
'name' => 'Tracking number',
'id' => 'tracking_number',
'type' => 'text',
) );
$cmb->add_field( array(
'name' => 'Tracking URL',
'id' => 'tracking_url',
'type' => 'text_url',
'protocols' => array( 'http', 'https' ),
) );
}
// Examine the tracking url and return a provider name.
function dcwd_get_tracking_provider_from_url( $url ) {
if ( strpos( $url, 'usps.com' ) !== false ) {
return 'USPS';
}
if ( strpos( $url, 'fedex.com' ) !== false ) {
return 'FexEd';
}
if ( strpos( $url, 'ups.com' ) !== false ) {
return 'UPS';
}
// Add more as necessary.
// Unknown provider.
return null;
}
// If available, include the tracking information in the Completed Order email.
add_action( 'woocommerce_email_order_details', 'dcwd_add_tracking_info_to_order_completed_email', 5, 4 );
function dcwd_add_tracking_info_to_order_completed_email( $order, $sent_to_admin, $plain_text, $email ) {
/* // Only customers need to know about the tracking information.
if ( ! $sent_to_admin ) {
return;
}
*/
if ( 'customer_completed_order' == $email->id ) {
$order_id = $order->get_id();
$tracking_number = get_post_meta( $order_id, 'tracking_number', true );
$tracking_url = get_post_meta( $order_id, 'tracking_url', true );
// Quit if either tracking field is empty.
if ( empty( $tracking_number ) || empty( $tracking_url ) ) {
// Debugging code.
//error_log( sprintf( 'Order %d does not have both tracking number (%s) and url (%s)', $order_id, $tracking_number, $tracking_url ) );
//echo '<p>Ne pare rău, informațiile de urmărire nu sunt disponibile în acest moment.</p>';
return;
}
$tracking_provider = dcwd_get_tracking_provider_from_url( $tracking_url );
if ( $plain_text ) {
if ( ! empty( $tracking_provider ) ) {
printf( "\nComanda dumneavoastra a fost expediata. %s. Numărul de urmărire este %s și îl poți urmări la %s.\n", $tracking_provider, esc_html( $tracking_number ), esc_url( $tracking_url, array( 'http', 'https' ) ) );
}
else {
printf( "\nComanda dumneavoastra a fost expediata. Numărul de urmărire este %s și îl poți urmări la %s.\n", esc_html( $tracking_number ), esc_url( $tracking_url, array( 'http', 'https' ) ) );
}
}
else {
if ( ! empty( $tracking_provider ) ) {
printf( '<p>Your order has been shipped with <strong>%s</strong>. The tracking number is <strong>%s</strong>.</p>', $tracking_provider, esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
else {
printf( '<p>Comanda dumneavoastra a fost expediata. Numărul de urmărire este <strong>%s</strong>.</p>', esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
}
}
}
// Display tracking information in My Account area.
add_action( 'woocommerce_view_order', 'dcwd_add_tracking_info_to_view_order_page', 5 );
function dcwd_add_tracking_info_to_view_order_page( $order_id ) {
$tracking_number = get_post_meta( $order_id, 'tracking_number', true );
$tracking_url = get_post_meta( $order_id, 'tracking_url', true );
// Quit if either tracking field is empty.
if ( empty( $tracking_number ) || empty( $tracking_url ) ) {
// Debugging code.
error_log( sprintf( 'Order %d does not have both tracking number (%s) and url (%s)', $order_id, $tracking_number, $tracking_url ) );
echo '<p>Ne pare rău, informațiile de urmărire nu sunt disponibile în acest moment.</p>';
return;
}
$tracking_provider = dcwd_get_tracking_provider_from_url( $tracking_url );
if ( ! empty( $tracking_provider ) ) {
printf( '<p>Comanda dvs. a fost expediată cu <strong>%s</strong>. Numărul de urmărire este <strong>%s</strong>.</p>', $tracking_provider, esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
else {
printf( '<p>Comanda dumneavoastra a fost expediata. Numărul de urmărire este <strong>%s</strong>.</p>', esc_url( $tracking_url, array( 'http', 'https' ) ), esc_html( $tracking_number ) );
}
}
function add_file_types_to_uploads($file_types){
$new_filetypes = array();
$new_filetypes['svg'] = 'image/svg+xml';
$file_types = array_merge($file_types, $new_filetypes );
return $file_types;
}
add_filter('upload_mimes', 'add_file_types_to_uploads');
function flatsome_result_count_and_catalog_ordering_remover() {
remove_action( 'flatsome_category_title_alt', 'woocommerce_result_count', 20);
}
add_action('template_redirect','flatsome_result_count_and_catalog_ordering_remover');
add_filter( 'wc_add_to_cart_message_html', '__return_false' );
add_action( 'wp_print_scripts', 'de_script', 100 );
function de_script() {
wp_dequeue_script( 'wc-cart-fragments' );
return true;
}
/**
* #snippet Remove Additional Information Tab # WooCommerce Single Product Page
* #how-to Get CustomizeWoo.com FREE
* #author Rodolfo Melogli
* #testedwith WooCommerce 3.8
* #donate $9 https://businessbloomer.com/bloomer-armada/
*/
add_filter( 'woocommerce_product_tabs', 'bbloomer_remove_product_tabs', 9999 );
function bbloomer_remove_product_tabs( $tabs ) {
unset( $tabs['additional_information'] );
return $tabs;
}
/**
* Hide shipping rates when free shipping is available.
* Updated to support WooCommerce 2.6 Shipping Zones.
*
* #param array $rates Array of rates found for the package.
* #return array
*/
function my_hide_shipping_when_free_is_available( $rates ) {
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );
add_filter( 'woocommerce_default_address_fields', 'customise_postcode_fields' );
function customise_postcode_fields( $address_fields ) {
$address_fields['postcode']['required'] = false;
return $address_fields;
}
if ( function_exists( 'yith_affiliates_install' ) ) {
if ( ! function_exists( 'yith_wcaf_show_dashboard_links_call_back' ) ) {
function yith_wcaf_show_dashboard_links_call_back() {
return 'yes';
}
}
add_filter( 'yith_wcaf_show_dashboard_links', 'yith_wcaf_show_dashboard_links_call_back' );
}
Related
I have created a custom checkout field related to packaging and with different price options.
It works nicely if I complete my order, all options are saved and appearing on thank you page/order email/admin edit order.
But, the issue is that if I select an option from this custom field and then continue browsing to another page, if I then go to checkout page again, the previously selected option is not displayed, somehow forgotten.
Can someone help me with adjustments to my code so that the options are saved and not forgotten?
Code is this (taken from this topic Add a dynamic fee based on a select field in WooCommerce Checkout and adjusted to suit my needs):
//Add a custom select fields for packing option fee
add_action( 'woocommerce_checkout_before_order_review', 'checkout_shipping_form_packing_addition', 40 );
function checkout_shipping_form_packing_addition( ) {
$domain = 'woocommerce';
echo '<tr class="packing-select"><th><h3>' . __('Packaging', $domain) . '</h3></th><td>';
$chosen = WC()->session->get('chosen_packing');
// Add a custom checkbox field
woocommerce_form_field( 'chosen_packing', array(
'type' => 'select',
'label' => __('Choose regular or gift-wrap packaging:', $domain ),
'class' => array( 'form-row-wide packing' ),
'options' => array(
'' => __("Select an option:", $domain),
'bag' => sprintf( __("Regular (free)", $domain), strip_tags( wc_price(0.00) ) ),
'box1' => sprintf( __("Gift-wrap (1): 0,50€", $domain), strip_tags( wc_price(0.50) ) ),
'box2' => sprintf( __("Gift-wrap (2): 1,00€", $domain), strip_tags( wc_price(1.00) ) ),
'box3' => sprintf( __("Gift-wrap (3): 1,50€", $domain), strip_tags( wc_price(1.50) ) ),
'box4' => sprintf( __("Gift-wrap (4): 2,00€", $domain), strip_tags( wc_price(2.00) ) ),
'box5' => sprintf( __("Gift-wrap (5): 2,50€", $domain), strip_tags( wc_price(2.50) ) ),
'box6' => sprintf( __("Gift-wrap (6): 3,00€", $domain), strip_tags( wc_price(3.00) ) ),
'box7' => sprintf( __("Gift-wrap (7): 3,50€", $domain), strip_tags( wc_price(3.50) ) ),
'box8' => sprintf( __("Gift-wrap (8): 4,00€", $domain), strip_tags( wc_price(4.00) ) ),
'box9' => sprintf( __("Gift-wrap (9): 4,50€", $domain), strip_tags( wc_price(4.50) ) ),
'box10' => sprintf( __("Gift-wrap (10+): 5,00€", $domain), strip_tags( wc_price(5.00) ) ),
),
'required' => true,
), $chosen );
echo '</th><td>';
}
// jQuery - Ajax script
add_action( 'wp_footer', 'checkout_shipping_packing_script' );
function checkout_shipping_packing_script() {
// Only checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
WC()->session->__unset('chosen_packing');
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'select#chosen_packing', function(){
var p = $(this).val();
console.log(p);
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'woo_get_ajax_data',
'packing': p,
},
success: function (result) {
$('body').trigger('update_checkout');
console.log('response: '+result); // just for testing | TO BE REMOVED
},
error: function(error){
console.log(error); // just for testing | TO BE REMOVED
}
});
});
});
</script>
<?php
endif;
}
// Php Ajax (Receiving request and saving to WC session)
add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' );
function woo_get_ajax_data() {
if ( isset($_POST['packing']) ){
$packing = sanitize_key( $_POST['packing'] );
WC()->session->set('chosen_packing', $packing );
echo json_encode( $packing );
}
die(); // Alway at the end (to avoid server error 500)
}
// 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( 'chosen_packing' ); // Dynamic packing fee
if ( $packing_fee === 'bag' ) {
$label = __("Regular (free)", $domain);
$cost = 0.00;
} elseif ( $packing_fee === 'box1' ) {
$label = __("Giftwrap (1)", $domain);
$cost = 0.50;
} elseif ( $packing_fee === 'box2' ) {
$label = __("Giftwrap (2)", $domain);
$cost = 1.00;
} elseif ( $packing_fee === 'box3' ) {
$label = __("Giftwrap (3)", $domain);
$cost = 1.50;
} elseif ( $packing_fee === 'box4' ) {
$label = __("Giftwrap (4)", $domain);
$cost = 2.00;
} elseif ( $packing_fee === 'box5' ) {
$label = __("Giftwrap (5)", $domain);
$cost = 2.50;
} elseif ( $packing_fee === 'box6' ) {
$label = __("Giftwrap (6)", $domain);
$cost = 3.00;
} elseif ( $packing_fee === 'box7' ) {
$label = __("Giftwrap (7)", $domain);
$cost = 3.50;
} elseif ( $packing_fee === 'box8' ) {
$label = __("Giftwrap (8)", $domain);
$cost = 4.00;
} elseif ( $packing_fee === 'box9' ) {
$label = __("Giftwrap (9)", $domain);
$cost = 4.50;
} elseif ( $packing_fee === 'box10' ) {
$label = __("Giftwrap (10+)", $domain);
$cost = 5.00;
}
if ( isset($cost) )
$cart->add_fee( $label, $cost );
}
// Field validation, as this packing field is required
add_action('woocommerce_checkout_process', 'packing_field_checkout_process');
function packing_field_checkout_process() {
// Check if set, if its not set add an error.
if ( isset($_POST['chosen_packing']) && empty($_POST['chosen_packing']) )
wc_add_notice( __( "<strong>Packaging</strong> is a required field.", "woocommerce" ), 'error' );
}
Excuse my linguistic mistakes, english is not my native language.
I'm trying to make a button that changes my order status, but it can only appear on the view-quote page when the order status is at: ywraq-pending
I'm trying this code, but it shows up in all statuses:
function customer_order_confirm_args( $order_id ) {
return array(
'url' => wp_nonce_url( add_query_arg( 'complete_order', $order_id ) , 'wc_complete_order' ),
'name' => __( 'Aprovar Orçamento', 'woocommerce' )
);
}
// Add a custom action button to processing orders (My account > Orders)
add_filter( 'woocommerce_my_account_my_orders_actions', 'complete_action_button_my_accout_orders', 50, 2 );
function complete_action_button_my_accout_orders( $actions, $order ) {
if ( $order->has_status( 'ywraq-pending' ) ) {
$actions['order_confirmed'] = customer_order_confirm_args( $order->get_id() );
}
return $actions;
}
// Add a custom button to processing orders (My account > View order)
add_action( 'woocommerce_order_details_after_order_table', 'complete_action_button_my_accout_order_view' );
function complete_action_button_my_accout_order_view( $order ){
// Avoiding displaying buttons on email notification
if( is_wc_endpoint_url( 'view-quote' ) ) {
$data = customer_order_confirm_args( $order->get_id() );
echo '<div style="margin:16px 0 24px;">
<a class="button" href="'.$data['url'].'">'.$data['name'].'</a>
</div>';
}
}
// Change order status and display a message
add_action( 'template_redirect', 'action_complete_order_status' );
function action_complete_order_status( $query ) {
if ( ( is_wc_endpoint_url( 'orders' )
|| is_wc_endpoint_url( 'view-quote' ) )
&& isset( $_GET['complete_order'] )
&& $_GET['complete_order'] > 1
&& isset($_GET['_wpnonce'])
&& wp_verify_nonce($_GET['_wpnonce'], 'wc_complete_order') )
{
$order = wc_get_order( absint($_GET['complete_order']) );
if ( is_a($order, 'WC_Order') ) {
// Change order status to "ywraq-accepted"
$order->update_status( 'ywraq-accepted', __('Approvado pelo cliente', 'woocommerce') ) ;
// Add a notice (optional)
wc_add_notice( sprintf( __( 'Pedido #%s foi aprovado', 'woocommerce' ), $order->get_id() ) );
// Remove query args
wp_redirect( esc_url( remove_query_arg( array( 'complete_order', '_wpnonce' ) ) ) );
exit();
}
}
}
Can anybody help me?
If I understood your question clearly, you missed checking order status in the complete_action_button_my_accout_order_view function, so, you can achieve that with this code:
function customer_order_confirm_args( $order_id ) {
return array(
'url' => wp_nonce_url( add_query_arg( 'complete_order', $order_id ) , 'wc_complete_order' ),
'name' => __( 'Aprovar Orçamento', 'woocommerce' )
);
}
// Add a custom action button to processing orders (My account > Orders)
add_filter( 'woocommerce_my_account_my_orders_actions', 'complete_action_button_my_accout_orders', 50, 2 );
function complete_action_button_my_accout_orders( $actions, $order ) {
if ( $order->has_status( 'ywraq-pending' ) ) {
$actions['order_confirmed'] = customer_order_confirm_args( $order->get_id() );
}
return $actions;
}
// Add a custom button to processing orders (My account > View order)
add_action( 'woocommerce_order_details_after_order_table', 'complete_action_button_my_accout_order_view' );
function complete_action_button_my_accout_order_view( $order ){
// Avoiding displaying buttons on email notification && only for orders with ywraq-pending status
if( is_wc_endpoint_url( 'view-quote' )
&& $order->has_status( 'ywraq-pending' ) ) {
$data = customer_order_confirm_args( $order->get_id() );
echo '<div style="margin:16px 0 24px;"><a class="button" href="'.$data['url'].'">'.$data['name'].'</a></div>';
}
}
// Change order status and display a message
add_action( 'template_redirect', 'action_complete_order_status' );
function action_complete_order_status( $query ) {
if ( ( is_wc_endpoint_url( 'orders' )
|| is_wc_endpoint_url( 'view-quote' ) )
&& isset( $_GET['complete_order'] )
&& $_GET['complete_order'] > 1
&& isset($_GET['_wpnonce'])
&& wp_verify_nonce($_GET['_wpnonce'], 'wc_complete_order') )
{
$order = wc_get_order( absint($_GET['complete_order']) );
if ( is_a($order, 'WC_Order') ) {
// Change order status to "ywraq-accepted"
$order->update_status( 'ywraq-accepted', __('Approvado pelo cliente', 'woocommerce') ) ;
// Add a notice (optional)
wc_add_notice( sprintf( __( 'Pedido #%s foi aprovado', 'woocommerce' ), $order->get_id() ) );
// Remove query args
wp_redirect( esc_url( remove_query_arg( array( 'complete_order', '_wpnonce' ) ) ) );
exit();
}
}
}
I am using a plugin that is creating a custom payment type where the user can fill in a custom payment ID. The thing is, I want that custom payment ID stored in an ACF field as post meta on the WooCommerce order edit page. I have created an ACF field named 'kkpayment' for this task. I figured the rest should be done using update_field($selector, $value, [$post_id]);. I have created a PHP function for this task. However, my code doesn't seem to work. Am I missing something obvious?
My function for updating the ACF field:
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta_acf' );
function custom_payment_update_order_meta_acf( $order_id ) {
$transaction = get_post_meta( $order->id, 'transaction', true );
if($_POST['payment_method'] = 'custom')
return $transaction;
update_field('kkpayment', $transaction, $order_id);
}
The custom payment is made with this code:
<?php
/*
Plugin Name: KK Payment Gateway
Description: Modtag betaling med kontostreng
Author: Arvin Aliari & Tobias Hyrup
Author URI: https://aliari.dk
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Baseret på StackOverlow: https://stackoverflow.com/questions/17081483/custom-payment-method-in-woocommerce
*
* Tilpasninger til dette projekt, se linje 135 - 161
*
*
*
* Custom Payment Gateway.
*
* Provides a Custom Payment Gateway.
*/
add_action('plugins_loaded', 'init_custom_gateway_class');
function init_custom_gateway_class(){
class WC_Gateway_Custom extends WC_Payment_Gateway {
public $domain;
/**
* Constructor for the gateway.e Number
*/
public function __construct() {
$this->domain = 'custom_payment';
$this->id = 'custom';
$this->icon = apply_filters('woocommerce_custom_gateway_icon', '');
$this->has_fields = false;
$this->method_title = __( 'Prisme', $this->domain );
$this->method_description = __( 'Tag i mod betaling fra Prisme.', $this->domain );
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->instructions = $this->get_option( 'instructions', $this->description );
$this->order_status = $this->get_option( 'order_status', 'completed' );
// Actions
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );
// Customer Emails
add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
}
/**
* Initialise Gateway Settings Form Fields.
*/
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Aktiver/Deaktiver', $this->domain ),
'type' => 'checkbox',
'label' => __( 'Tillad betaling med kontostreng', $this->domain ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Titel', $this->domain ),
'type' => 'text',
'description' => __( 'Angiver den titel som brugeren ser under checkout.', $this->domain ),
'default' => __( 'Betaling med kontostreng', $this->domain ),
'desc_tip' => true,
),
'order_status' => array(
'title' => __( 'Ordrestatus', $this->domain ),
'type' => 'select',
'class' => 'wc-enhanced-select',
'description' => __( 'Vælg hvilken status du ønsker efter chekout.', $this->domain ),
'default' => 'wc-completed',
'desc_tip' => true,
'options' => wc_get_order_statuses()
),
'description' => array(
'title' => __( 'Beskrivelse', $this->domain ),
'type' => 'textarea',
'description' => __( 'Beskrivelse af betalingsmetoden som brugerene ser under chekout.', $this->domain ),
'default' => __('Payment Information', $this->domain),
'desc_tip' => true,
),
'instructions' => array(
'title' => __( 'Instruktioner', $this->domain ),
'type' => 'textarea',
'description' => __( 'Besked som brugerene vil se på efter gennemført ordre.', $this->domain ),
'default' => '',
'desc_tip' => true,
),
);
}
/**
* Output for the order received page.
*/
public function thankyou_page() {
if ( $this->instructions )
echo wpautop( wptexturize( $this->instructions ) );
}
/**
* Add content to the WC emails.
*
* #access public
* #param WC_Order $order
* #param bool $sent_to_admin
* #param bool $plain_text
*/
public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
if ( $this->instructions && ! $sent_to_admin && 'custom' === $order->payment_method && $order->has_status( 'on-hold' ) ) {
echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
}
}
public function payment_fields(){
if ( $description = $this->get_description() ) {
echo wpautop( wptexturize( $description ) );
}
?>
<div id="custom_input">
<p class="form-row form-row-wide">
<label for="transaction" class=""><?php _e('26-cifret kontostreng:', $this->domain); ?></label>
<input type="text" class="" name="transaction" id="transaction" placeholder="12345-1234-123-123456789-123-12" value="" style="width: 225px;">
</p>
<p style="opacity: 0.75; margin-top:-10px; font-size: 13.5px;">Eks: 12345-1234-123-123456789-123-12</p>
<p>Hvis du ikke har en kontostreng, så kontakt din nærmeste leder eller økonomimedarbejder.</p>
</div>
<?php
}
public function validate_fields(){
$paymentString = $_POST['transaction'];
$strLength = strlen($paymentString);
/*$stringContains = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{7}[-]\d{3}[-]\d{2}$/", $paymentString);*/
$stringContains = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{9}[-]\d{3}[-]\d{2}$/", $paymentString);
if($stringContains && !empty($_POST['transaction']) && $_POST['transaction'] != "") {
return true;
} else {
$stringOldPattern = preg_match("/^\d{5}[-]\d{4}[-]\d{3}[-]\d{7}[-]\d{3}[-]\d{2}$/", $paymentString);
if($stringOldPattern){
wc_add_notice( "Ugyldig kontostreng - Husk at bruge det nye format på 26 cifre der inkluderer funktionskode. Tjek at du har indtastet kontostrengen korrekt. Eksempel: 12345-1234-123-123456789-123-12", 'error' );
} else {
wc_add_notice( "Ugyldig kontostreng - Tjek at du har indtastet kontostrengen korrekt. Eksempel: 12345-1234-123-123456789-123-12", 'error' );
}
return false;
}
}
/**
* Process the payment and return the result.
*
* #param int $order_id
* #return array
*/
public function process_payment( $order_id ) {
$order = wc_get_order( $order_id );
$status = 'wc-' === substr( $this->order_status, 0, 3 ) ? substr( $this->order_status, 3 ) : $this->order_status;
// Set order status
$order->update_status( $status, __( 'Checkout with custom payment. ', $this->domain ) );
// Reduce stock levels
$order->reduce_order_stock();
// Remove cart
WC()->cart->empty_cart();
// Return thankyou redirect
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
}
}
}
add_filter( 'woocommerce_payment_gateways', 'add_custom_gateway_class' );
function add_custom_gateway_class( $methods ) {
$methods[] = 'WC_Gateway_Custom';
return $methods;
}
add_action('woocommerce_checkout_process', 'process_custom_payment');
function process_custom_payment(){
if($_POST['payment_method'] != 'custom')
return;
if( !isset($_POST['transaction']) || empty($_POST['transaction']) )
//wc_add_notice( __( 'Angiv venligst dit 26-cifret kontostreng til Prisme', $this->domain ), 'error' );
wc_add_notice( __( 'Angiv venligst dit 26-cifret kontostreng til Prisme', ), 'error' );
}
/**
* Update the order meta with field value
*/
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta' );
function custom_payment_update_order_meta( $order_id ) {
if($_POST['payment_method'] != 'custom')
return;
// echo "<pre>";
// print_r($_POST);
// echo "</pre>";
// exit();
update_post_meta( $order_id, 'transaction', $_POST['transaction'] );
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'custom_checkout_field_display_admin_order_meta', 10, 1 );
function custom_checkout_field_display_admin_order_meta($order){
$method = get_post_meta( $order->id, '_payment_method', true );
if($method != 'custom')
return;
$transaction = get_post_meta( $order->id, 'transaction', true );
echo '<p><strong>'.__( '26 cifret kontostreng').':</strong> ' . $transaction . '</p>';
}
/**
* Add payment to metadata
*/
add_action( 'woocommerce_checkout_update_order_meta', 'custom_payment_update_order_meta_acf' );
function custom_payment_update_order_meta_acf( $order_id ) {
$transaction = get_post_meta( $order->id, 'transaction', true );
if($_POST['payment_method'] = 'custom')
return $transaction;
update_field('kkpayment', $transaction, $order_id);
}
Use this code to update acf field on successful transaction.
add_action( 'woocommerce_thankyou', 'bks_post_transaction_after_order_completion', 10, 1 );
function bks_post_transaction_after_order_completion( $order_id ) {
$order = wc_get_order( $order_id ); // phpcs:ignore.
$status = $order->get_status();
// Try to post only when order status is completed or processing.
if ( ! ( 'completed' === $status || 'processing' === $status ) ) {
return;
}
// get transaction.
$transaction = get_post_meta( $order->id, 'transaction', true );
update_field('kkpayment', $transaction, $order_id);
$order->update_meta_data( 'kkpayment', $transaction ); // phpcs:ignore
$order->save();
}
Based on Update fee dynamically based on radio buttons in Woocommerce checkout anser code. I'm trying to make it work with different packaging options on WooCommerce checkout.
The idea is to be able to provide options for gift wrapping, packaging in a bag and so forth.
Problem is, it gives me selectable options but it's all messed up as it is printing out the HTML for the tags and what not.
This is the code I am working with:
add_action( 'woocommerce_form_field_radio', 'gift_bag_none', 20, 4 );
function gift_bag_none( $field, $key, $args, $value ) {
if ( ! empty( $args['options'] ) && is_checkout() ) {
$field = str_replace( '</label><input ', '</label><br><input ', $field );
$field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
}
return $field;
}
add_action( 'woocommerce_cart_calculate_fees', 'gift_bag_none_fee', 20, 1 );
function gift_bag_none_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
$packing_fee = WC()->session->get( 'chosen_packing' );
if( $packing_fee === 'box' )
$fee = 29.00;
else if( $packing_fee === 'none' )
$fee = 0.00;
else if( $packing_fee === 'both' )
$fee = 25.00;
else
$fee = 5.00;
$cart->add_fee( __( 'Packaging Cost', 'woocommerce' ), $fee );
}
add_action( 'woocommerce_review_order_after_shipping', 'checkout_packing_addition', 20 );
function checkout_packing_addition() {
$domain = 'woocommerce';
echo '<tr><th>' . __('Packaging Options', $domain) . '</th><td>';
echo '<tr class="packing-select"><th>' . __('In a bag?<br>Boxed and wrapped as gift?<br><span style="color:red;">Boxed, wrapped and in a bag?</span><br>Or just the product?', $domain) . '</th><td>';
$chosen = WC()->session->get('chosen_packing');
$chosen = empty($chosen) ? WC()->checkout->get_value('radio_packing') : $chosen;
$chosen = empty($chosen) ? 'none' : $chosen;
woocommerce_form_field( 'radio_packing', array(
'type' => 'radio',
'class' => array( 'form-row-wide packing' ),
'options' => array(
'bag' => __('Yes, give it to me in a bag for '.wc_price(5.00), $domain),
'box' => __('Giftbox + Wrapping for '.wc_price(29.00), $domain),
'both' => __('Wrapped Giftbox in a Bag for '.wc_price(25.00), $domain),
'none' => __('Just the product at no extra cost '.wc_price(0.00), $domain)
),
'default' => $chosen,
), $chosen );
echo '</td></tr>';
}
add_action( 'wp_footer', 'checkout_packing_script' );
function checkout_packing_script(){ ?>
<script type="text/javascript">
jQuery( function($) {
$('form.checkout').on('change', 'input[name=radio_packing]', function(e){
e.preventDefault();
var p = $(this).val();
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'woo_get_ajax_data',
'packing': p,
},
success: function (result) {
$('body').trigger('update_checkout');
},
error: function(error){
}
});
});
});
</script>
<?php
}
add_action('wp_ajax_woo_get_ajax_data', 'packing_ajax_data');
add_action('wp_ajax_nopriv_woo_get_ajax_data', 'packing_ajax_data');
function packing_ajax_data() {
if ( isset($_POST['packing']) ){
$packing = sanitize_key( $_POST['packing'] );
WC()->session->set('chosen_packing', $packing );
echo json_encode( $packing );
}
die();
}
Updated: 10/2021 - tested in WordPress 5.8.1 & WooCommerce 5.7.1
Your code has some minor mistakes
Use add_filter( 'woocommerce_form_field_radio' instead of add_action(..
Use strip_tags( wc_price() ) against wc_price()
So you get:
// Customizing WooCommerce radio form field
function filter_woocommerce_form_field_radio( $field, $key, $args, $value ) {
// Specific key and apply on checkout page
if ( ! empty( $args['options'] ) && $key == 'radio_packing' && is_checkout() ) {
$field = str_replace( '</label><input ', '</label><br><input ', $field );
$field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
}
return $field;
}
add_filter( 'woocommerce_form_field_radio', 'filter_woocommerce_form_field_radio', 20, 4 );
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Dynamic packing fee
$packing_fee = WC()->session->get( 'chosen_packing' );
// Determine packing fee
if ( $packing_fee === 'bag' ) {
$fee = 5.00;
} else if( $packing_fee === 'box' ) {
$fee = 29.00;
} else if( $packing_fee === 'both' ) {
$fee = 25.00;
} else {
$fee = 0.00;
}
// Add fee: name - amount - taxable
$cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee, true );
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
// Add a custom radio fields for packaging selection
function action_woocommerce_review_order_after_shipping() {
// Domain
$domain = 'woocommerce';
// Output
echo '<tr class="packing-select"><th>' . __('Packing options', $domain ) . '</th><td>';
$chosen = WC()->session->get( 'chosen_packing' );
$chosen = empty( $chosen ) ? WC()->checkout->get_value( 'radio_packing' ) : $chosen;
$chosen = empty( $chosen ) ? 'none' : $chosen;
// Add a custom checkbox field
woocommerce_form_field( 'radio_packing', array(
'type' => 'radio',
'class' => array( 'form-row-wide packing' ),
'options' => array(
'bag' => sprintf( __( 'Yes, give it to me in a bag for %s', $domain ), strip_tags( wc_price( 5.00 ) ) ),
'box' => sprintf( __( 'Giftbox + Wrapping for %s', $domain ), strip_tags( wc_price( 29.00 ) ) ),
'both' => sprintf( __( 'Wrapped Giftbox in a Bag for %s', $domain ), strip_tags( wc_price( 25.00 ) ) ),
'none' => sprintf( __( 'Just the product at no extra cost %s', $domain ), strip_tags( wc_price( 0.00 ) ) )
),
'default' => $chosen,
), $chosen );
echo '</td></tr>';
}
add_action( 'woocommerce_review_order_after_shipping', 'action_woocommerce_review_order_after_shipping', 10, 0 );
// jQuery - Ajax script
function action_wp_footer() {
if ( ! is_checkout() )
return; // Only checkout page
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name=radio_packing]', function(e){
e.preventDefault();
var p = $(this).val();
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'woo_get_ajax_data',
'packing': p,
},
success: function (result) {
$('body').trigger('update_checkout');
console.log('response: '+result); // just for testing | TO BE REMOVED
},
error: function(error){
console.log(error); // just for testing | TO BE REMOVED
}
});
});
});
</script>
<?php
}
add_action( 'wp_footer', 'action_wp_footer', 10, 0 );
// Php Ajax (Receiving request and saving to WC session)
function woo_get_ajax_data() {
if ( isset($_POST['packing']) ){
$packing = sanitize_key( $_POST['packing'] );
WC()->session->set('chosen_packing', $packing );
echo json_encode( $packing );
}
die(); // Always at the end (to avoid server error 500)
}
add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' );
I am adding a 'Title' field to my Woocommerce Billing and Shipping Addresses. All works with PHP 7, but when I upgrade to 7.1 or 7.2 the orders page in WooCommerce falls over and can't display orders correctly. So I can only see the first order even though there are 3 pages of orders and if I click on that one order it only displays part of the details, no addresses at all.
// Add Title field in billing address display
add_filter( 'woocommerce_order_formatted_billing_address',
'custom_add_title_formatted_billing_address', 1, 1 );
function custom_add_title_formatted_billing_address( $fields, $order ) {
$fields['title'] = $order->billing_title;
return $fields;
}
add_filter( 'woocommerce_my_account_my_address_formatted_address',
'custom_my_account_my_address_formatted_address', 1, 1 );
function custom_my_account_my_address_formatted_address( $fields, $customer_id,
$type ) {
if ( $type == 'billing' ) {
$fields['title'] = get_user_meta( $customer_id, 'billing_title', true );
}
return $fields;
}
add_filter( 'woocommerce_address_to_edit', 'custom_address_to_edit', 1 );
function custom_address_to_edit( $address ) {
global $wp_query;
if ( isset( $wp_query->query_vars['edit-address'] ) && $wp_query-
>query_vars['edit-address'] != 'billing' ) {
return $address;
}
if ( ! isset( $address['billing_title'] ) ) {
$address['billing_title'] = array(
'label' => __( 'Title', 'your-domain' ),
'placeholder' => _x( 'Mr', 'placeholder', 'your-domain' ),
'required' => false, //change to false if you do not need this field
to be required
'class' => array( 'form-row-first' ),
'value' => get_user_meta( get_current_user_id(), 'billing_title',
true )
);
}
return $address;
}
add_filter( 'woocommerce_formatted_address_replacements',
'custom_formatted_address_replacements' );
function custom_formatted_address_replacements( $address, $args ) {
$address['{title}'] = '';
if ( ! empty( $args['title'] ) ) {
$address['{title}'] = __( 'Title', 'your-domain' ) . ' ' . $args['title'];
}
return $address;
}
add_filter( 'woocommerce_localisation_address_formats',
'custom_localisation_address_format', 1 );
function custom_localisation_address_format( $formats ) {
$formats['IT'] .= "\n\n{title}";
return $formats;
}
add_filter( 'woocommerce_admin_billing_fields', 'custom_admin_billing_fields',
1 );
function custom_admin_billing_fields( $fields ) {
$fields['title'] = array(
'label' => __( 'Title', 'your-domain' ),
'show' => true
);
return $fields;
}
add_filter( 'woocommerce_found_customer_details',
'custom_found_customer_details' );
function custom_found_customer_details( $customer_data ) {
$customer_data['billing_title'] = get_user_meta( $_POST['user_id'],
'billing_title', true );
return $customer_data;
}
add_filter( 'woocommerce_customer_meta_fields', 'custom_customer_meta_fields'
);
function custom_customer_meta_fields( $fields ) {
$fields['billing']['fields']['billing_title'] = array(
'label' => __( 'Title', 'woocommerce' )
);
return $fields;
}
Any ideas greatly appreciated.
This problem can come from the first hooked function, where $order->billing_title; is not correct as since Woocommerce 3, most of object properties can't be accessed directly. This is the case for $order the WC_Order Object instance. Instead you can use inherited WC_Data method get_meta().
There is also some mistakes in the hooks priority and arguments.
Try the following revisited code:
// Add Title field in billing address display
add_filter( 'woocommerce_order_formatted_billing_address', 'custom_add_title_formatted_billing_address', 10, 2 );
function custom_add_title_formatted_billing_address( $billing_address, $order ) {
$billing_address['title'] = $order->get_meta( '_billing_title');
return $billing_address;
}
add_filter( 'woocommerce_my_account_my_address_formatted_address', 'custom_my_account_my_address_formatted_address', 10, 3 );
function custom_my_account_my_address_formatted_address( $address, $customer_id, $address_type ) {
if ( $address_type == 'billing' ) {
$address['title'] = get_user_meta( $customer_id, 'billing_title', true );
}
return $address;
}
add_filter( 'woocommerce_address_to_edit', 'custom_address_to_edit', 10, 2 );
function custom_address_to_edit( $address, $load_address ) {
global $wp_query;
if ( isset( $wp_query->query_vars['edit-address'] ) && $wp_query->query_vars['edit-address'] != 'billing' ) {
return $address;
}
if ( ! isset( $address['billing_title'] ) ) {
$address['billing_title'] = array(
'label' => __( 'Title', 'your-domain' ),
'placeholder' => _x( 'Mr', 'placeholder', 'your-domain' ),
'required' => false, //change to false if you do not need this field to be required
'class' => array( 'form-row-first' ),
'value' => get_user_meta( get_current_user_id(), 'billing_title', true )
);
}
return $address;
}
add_filter( 'woocommerce_formatted_address_replacements', 'custom_formatted_address_replacements', 10, 2 );
function custom_formatted_address_replacements( $replacements, $args ) {
$replacements['{title}'] = '';
if ( ! empty( $args['title'] ) ) {
$replacements['{title}'] = __( 'Title', 'your-domain' ) . ' ' . $args['title'];
}
return $replacements;
}
add_filter( 'woocommerce_localisation_address_formats', 'custom_localisation_address_format', 10, 1 );
function custom_localisation_address_format( $formats ) {
$formats['IT'] .= "\n\n{title}";
return $formats;
}
add_filter( 'woocommerce_admin_billing_fields', 'custom_admin_billing_fields', 10, 1 );
function custom_admin_billing_fields( $billing_fields ) {
$billing_fields['title'] = array(
'label' => __( 'Title', 'your-domain' ),
'show' => true
);
return $billing_fields;
}
add_filter( 'woocommerce_found_customer_details', 'custom_found_customer_details', 10, 1 );
function custom_found_customer_details( $customer_data ) {
$customer_data['billing_title'] = get_user_meta( $_POST['user_id'], 'billing_title', true );
return $customer_data;
}
add_filter( 'woocommerce_customer_meta_fields', 'custom_customer_meta_fields', 10, 1 );
function custom_customer_meta_fields( $show_fields ) {
$show_fields['billing']['fields']['billing_title']['label'] = __( 'Title', 'woocommerce' );
return $show_fields;
}
I don't see anything else that can be making a problem in PHP 7.2…