Hooks (action & filter)

Hooks (action & filter)

Hooks in WordPress essentially allow you to change or add code without editing core files. They are used extensively throughout WordPress and WooCommerce and are very useful for developers.

Read more about action and filter hooks here:

In Klarna Checkout for WooCommerce there are some action and filter hooks available, mainly for modifying the order data sent to Klarna and how the checkout page should be displayed.


How and where to insert the code?


To get the functions exemplified in this section to work you need to add the code to your theme’s functions.php. You can add it as its own plugin or through the Code Snippets plugin, or something similar of your choice.


Actions


The appearance of the Klarna Checkout page comes with a two-column layout. In this layout we have shopping cart, delivery options and customer order note in the left-hand column while Klarna’s checkout (where you enter personal information and choose payment method) is shown in the right-hand column.

Sometimes you need to change the design of the checkout page and with Klarna Checkout for WooCommerce it is possible in a couple of different ways.


Simple CSS changes

If you only want to make minor design changes, CSS adjustments may be enough to get you where you want.For example, to create a checkout page with a single-column layout, add the following CSS to your theme:

#kco-wrapper #kco-order-review,
#kco-wrapper #kco-iframe {
	width: 100%;
	float: none;
	clear: both;
}

Remove, add and move with action hooks

If you want to make some more extensive changes to the layout of the checkout page, it is recommended to work with action hooks.

The checkout template file

templates/klarna-checkout.php

On the Klarna Checkout template page, there are several action hooks you can use to add code or content. These hooks have the following names:

  • woocommerce_before_checkout_form
  • kco_wc_before_order_review
  • kco_wc_after_order_review
  • kco_wc_before_snippet
  • kco_wc_after_snippet
  • woocommerce_after_checkout_form

You can find their location here:

Through these action hooks, you can easily add information to different locations on the checkout page.


Create your own template file

If you need to make changes that can’t be accomplished via action hooks, then you are able to overwrite the checkout template file via your theme. The plugin supports WooCommerce’s way of handling template files.

The template file used for displaying Klarna Checkout is called klarna-checkout.php and it is located in the templates folder in the plugin. To overwrite the file, copy it from the plugin, then paste it into the /woocommerce folder in your theme. Now you have the opportunity to make the changes you want. Keep in mind that the action hooks woocommerce_before_checkout_form and woocommerce_after_checkout_form must remain for the plugin to work properly. 


Filters


Action filters are used to modify data before sending it to an external service, rendering it in the browser or storing it in a database. The most common occasion this might be used in the plugin is if you want to modify the order/cart data sent to Klarna before the KCO checkout is rendered.


Modify order data sent to Klarna

classes/class-kco-api.php
To modify the order data sent to Klarna (actually the cart data since the WooCommerce order isn’t created until after the purchase is finalized in Klarna Checkout), you use the filter kco_wc_api_request_args as described in the following example:

/**
 * Use together with Klarna Checkout for WooCommerce (v3 platform)
 * https://wordpress.org/plugins/klarna-checkout-for-woocommerce/
 *
 * Filter the purchase country sent to Klarna.
 * Add this code to your themes functions.php file or include it in a separate functionality plugin (https://css-tricks.com/wordpress-functionality-plugins/).
 **/

add_filter( 'kco_wc_api_request_args', 'krokedil_change_klarna_country' );

function krokedil_change_klarna_country( $request_args ) {
	
	if ( method_exists( WC()->customer, 'shipping_country' ) ) {
		$request_args['purchase_country'] = WC()->customer->shipping_country;
	}
	return $request_args;
}

Information about available parameters in Klarnas API can be found here.


Change the locale sent to Klarna

The filter hook kco_locale let you change the locale that is sent to Klarna. The locale is the combination of a two-letter language code (see RFC 5646), and country code (see ISO 3166-1 alpha-2) separated by a dash (e.g., en-US).

Example: https://docs.klarna.com/klarna-payments/in-depth-knowledge/puchase-countries-currencies-locales/#data-mapping

function kco_custom_locale( $locale ) {
	return 'en-SE';
}

add_filter( 'kco_locale', 'kco_custom_locale');

Anonymize product names sent to Klarna

To modify the order data sent to Klarna, to anonymize the product names, you can add this filter. You can use the Code Snippets plugin, or something similar of your choice.

add_filter(
	'kco_wc_api_request_args',
	function ( $request_args ) {
		foreach ( $request_args['order_lines'] as $index => $order_line ) {
			$request_args['order_lines'][ $index ]['name'] = md5( $order_line['name'] );
		}
		return $request_args;
	}
);

This will result in the product names sent to Klarna will be just a random series of letters and numbers:

The real name of the product is still visible in the WooCommerce order. It is only in Klarna’s system where the name is anonymized/censored.


Display Klarna Checkout even on free orders

If you have a coupon that brings the total order value down to zero making the order free for the customer, by default this will show the standard WooCommerce checkout instead of the Klarna Checkout. If you would rather want to show the Klarna Checkout for this you can use the filter kco_check_if_needs_payment. And return false instead of true to this filter.

/**
 * Use together with Klarna Checkout for WooCommerce (v3 platform)
 * https://wordpress.org/plugins/klarna-checkout-for-woocommerce/
 *
 * Filter to change if you want the Klarna Checkout iFrame to display on free orders or not.
 * For example after a coupon has been used.
 */

add_filter( 'kco_check_if_needs_payment', 'kco_change_check_if_needs_payment' );
function kco_change_check_if_needs_payment( $bool ) {
  return false;
}

Set a forced purchase country

If you need to set a forced purchase country for any reason other then what the store country is and you don’t want to use geolocation, then you can use this snippet to do so. Simply change SE for any other two letter country code that you want to use.

<?php
/** 
 * Filter to change the purchase country. Overwrites the WooCommerce default, and sets a forced purchase country.
 * Change SE to whatever value you want, 2 letter country codes only.
 */

add_filter( 'kco_wc_api_request_args', 'kco_wc_change_purchase_country' );
/**
 * Changes the purchase country.
 *
 * @param array $request_args The KCO v3 request args.
 * @return array
 */
function kco_wc_change_purchase_country( $request_args ) {
    $request_args['purchase_country'] = 'SE';
    return $request_args;
}

Only accept purchases from customer over 18 years of age.

Code example on how to only accept purchases from people over 18 years of age with Klarna Checkout for WooCommerce

This only works if Klarna has activated the “Allow merchant to read customers national identification number” setting in your account…

/**
 * Klarna Checkout for WooCommerce (v3 platform)
 * https://wordpress.org/plugins/klarna-checkout-for-woocommerce/
 *
 * Only accept purchases from customer over 18 years of age.
 * This will only work if Klarna has activated the "Allow merchant to read customers national identification number"setting in your account at Klarna.
 * Current version of this snippet only works for 2.x versions of KCO. For older versions please use the older version of this snippet.
 */

 add_filter( 'kco_wc_api_request_args', 'my_kco_wc_api_request_args' );
 /**
  * Sets the option so DOB is mandatory in the checkout.
  *
  * @param array $request_args The request args for Klarna Checkout.
  * @return array
  */
function my_kco_wc_api_request_args( $request_args ) {
	$request_args['options']['national_identification_number_mandatory'] = true;
	return $request_args;
}

add_action( 'woocommerce_checkout_process', 'kco_validate_age' );
 /**
  * Validates the age of the customer. Prevents customers from under the given age to complete an order.
  *
  * @return void
  */
function kco_validate_age() {
	if ( isset( WC()->session ) && 'kco' === WC()->session->get( 'chosen_payment_method' ) ) {
		if ( ! empty( WC()->session->get( 'kco_wc_order_id' ) ) ) {
			$klarna_order = KCO_WC()->api->get_klarna_order( WC()->session->get( 'kco_wc_order_id' ) );

			// Date of birth is not available for organizations.
			if ( 'organization' === $klarna_order['customer']['type'] ) {
				return;
			}

			$birthday = new DateTime( $klarna_order['customer']['date_of_birth'] );
			$now      = new DateTime();
			$age      = $now->diff( $birthday );
			if ( $age->y < 18 ) {
				wc_add_notice( __( 'You must be 18 years or older.', 'klarna-checkout-for-woocommerce' ), 'error' );
			}
		}
	}
}

Add Cancellation terms sent to Klarna

URL for the cancellation terms page of the merchant. The URL will be displayed in the email that is sent to the customer after the order is captured (max 2000 characters).


Add additional checkboxes

There are times when you might want to add an additional checkbox, like a newsletter sign-up or something else.

To show the checkbox with associated text in the Klarna Checkout we need to send the info about this to Klarna along with all other order/cart information. We do this by adding the filter kco_additional_checkboxes in the following way:

<?php
/**
 * Filter the additional checkboxes to add to the Klarna Checkout iframe. Works with Klarna Checkout for WooCommerce 2.4.3 and above.
 */
add_filter( 'kco_additional_checkboxes', 'add_custom_checkboxes' );
function add_custom_checkboxes( $additional_checkboxes ) {
	$additional_checkboxes[] = array(
		'id'       => 'custom_checkbox', // The ID to be used in the backend to read when we get the order during the checkout process.
		'text'     => 'Custom checkbox', // The text that you want to display to the customer.
		'checked'  => false, // true if it should be automatically checked, false if not.
		'required' => true, // true if its required to be able to place an order, false if not.
	);
	return $additional_checkboxes;
}

Text – In the field text you can add the text that you want to display in connection with this checkbox.

Checked  – In the field checked you set whether you want the box checked (true) or unchecked (false) on the initial load of the checkout.

Required – In the field required you can set if this checkbox is required (true) or not (false) to be able to complete the order.

Save the result in the order

When the purchase is completed by the customer and are redirected to the Thank you page we can collect the information, which is whether the customer checked the box or not. We do this with the action hook kco_wc_confirm_klarna_order in the following way:

<?php
add_action( 'kco_wc_payment_complete', 'kco_process_checkboxes' );
function kco_process_checkboxes( $order_id ) {
	$klarna_order_id = get_post_meta( $order_id, '_transaction_id', true );
	$klarna_order    = KCO_WC()->api->get_klarna_order( $klarna_order_id );
​
	if ( isset( $klarna_order['merchant_requested']['additional_checkboxes'] ) ) {
		foreach ( $klarna_order['merchant_requested']['additional_checkboxes'] as $checkbox ) {
			if ( 'newsletter' === $checkbox['id'] && $checkbox['checked'] ) {
				// Do something with the newsletter checkbox.
			}
		}
	}
}

In this example our checkbox is for letting people subscribe to a newsletter through MailChimp in the way the plugin MailChimp for WooCommerce wants it. Here you need to change the name on the post meta field to the name of where your plugin saves the information. In our example the number 1 is saved in the post meta field mailchimp_woocommerce_is_subscribed if the customer has opted in to subscribe to the newsletter. The process of sending this information to the newsletter provider is something the plugin for the newsletter, in the case MailChimp for WooCommerce, handles. That is both outside of the Klarna plugin and the examples above.

Note that this is only an example on how you save the information with the order and we can’t guarantee that we have all the updated info on how a specific plugin other than our own handles things, so you need to look this up for yourself.

How and where to insert the code?

To get the function to work you need to add the code to your theme’s functions.php, as its own plugin or through the Code Snippets plugin.


Modify payment method icon

An icon is displayed next to the payment method name on the checkout page.

If you want to change this icon there is a filter available for that. 

By using the filter  wc_klarna_checkout_icon_html in the following way you can change it to your needs.

<?php
/**
 * Filter hook wc_klarna_checkout_icon_html
 * Modify the icon displayed for Klarna Checkout payment method in checkout.
 *
 * Add this code to your themes functions.php file or include it in a separate functionality plugin (https://css-tricks.com/wordpress-functionality-plugins/).
 */
add_filter( 'wc_klarna_checkout_icon_html', 'krokedil_wc_klarna_checkout_icon_html' );
function krokedil_wc_klarna_checkout_icon_html( $icon_html ) {
	// Standard image is https://cdn.klarna.com/1.0/shared/image/generic/logo/en_us/basic/logo_black.png?width=100.
	$icon_src   = 'https://x.klarnacdn.net/payment-method/assets/badges/generic/black/klarna.png?width=100';
	
	$new_icon_html  = '<img src="' . $icon_src . '" alt="Klarna Checkout"/>';
	
	// Return the modified image html.
	return $new_icon_html;
}

A set of different logos/badges to use can be found at the Klarna Developers site.