Actions & filters

Last modified:

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 for WooCommerce, there are a few action and filter hooks available.

You can also find all available hooks, including source code links, in the GitHub repository for Klarna for WooCommerce.

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 WordPress project. You can add it as its own plugin, through the Code Snippets plugin, your theme’s functions.php file or something similar of your choice.

Actions

Handle the Klarna modal closed event

kp_modal_closed

When the Klarna modal is closed, the kp_modal_closed action will be triggered.

Here is an example of how you could handle it depending on whether the purchase was aborted by the customer or rejected by Klarna:

/**
 * Handle the Klarna modal closed event.
 *
 * @param WC_Order $order The WooCommerce order.
 * @param bool     $reason TRUE if purchase aborted by the customer. FALSE if rejected by Klarna.
 * @return void
 */
function klarna_modal_closed( $order, $reason ) {
	if ( $reason ) {
		$order->add_order_note( 'Customer aborted.' );
	} else {
		$order->add_order_note( 'Rejected by Klarna.' );
	}

	$order->save();
}
add_action( 'kp_modal_closed', 'klarna_modal_closed', 10, 2 );

After a Klarna payment is accepted

wc_klarna_payments_accepted

Description

Fired when a Klarna payment is successfully accepted. Use this to run custom logic immediately after Klarna confirms a successful payment.

See also: wc_klarna_accepted below — an alias that fires at the same time and accepts the same arguments.

Timing

Fires inside kp_process_accepted(), which is called after the Klarna fraud status is determined to be ACCEPTED. This happens:

  1. During the checkout flow when the customer clicks “Pay” and Klarna immediately accepts the payment.
  2. During the Klarna Express Checkout (KEC) one-step flow when Klarna confirms a completed payment state.

Signature

do_action( 'wc_klarna_payments_accepted', $order_id, $response );
  • int $order_id — The WooCommerce order ID.
  • array $response — The full decoded response from Klarna’s place-order API call.

Example

/**
 * Send a custom confirmation email when a Klarna payment is accepted.
 *
 * @param int   $order_id The WooCommerce order ID.
 * @param array $response The Klarna API response.
 */
function mytheme_klarna_payment_accepted( $order_id, $response ) {
    $order = wc_get_order( $order_id );
    my_loyalty_points_system( $order );
}
add_action( 'wc_klarna_payments_accepted', 'mytheme_klarna_payment_accepted', 10, 2 );

wc_klarna_accepted

An alias for wc_klarna_payments_accepted. Both hooks fire at the exact same moment with the same arguments. This shorter hook name exists for cross-plugin compatibility.

Signature

do_action( 'wc_klarna_accepted', $order_id, $response );
  • int $order_id — The WooCommerce order ID.
  • array $response — The full decoded response from Klarna’s place-order API call.

When a Klarna payment is pending review

wc_klarna_payments_pending

Fired when Klarna’s fraud status for a payment is PENDING — meaning Klarna has not yet made a final decision and the order is placed On hold. The order is set to on-hold status automatically before this action fires.

See also: wc_klarna_pending below — an alias that fires at the same time.

Timing

Fires in three scenarios:

  1. During checkout when Klarna returns a PENDING fraud status after the customer clicks “Pay”.
  2. During the KEC one-step flow when the place-order call fails but the order should remain On hold.
  3. During the KEC one-step flow when the payment state is COMPLETED but place_order fails.

Signature

do_action( 'wc_klarna_payments_pending', $order_id, $response );
  • int $order_id — The WooCommerce order ID.
  • array $response — The full decoded response from Klarna’s place-order API call.

Example

/**
 * Notify the store owner when a Klarna payment is pending review.
 *
 * @param int   $order_id The WooCommerce order ID.
 * @param array $response The Klarna API response.
 */
function mytheme_klarna_payment_pending( $order_id, $response ) {
    $order = wc_get_order( $order_id );
    wp_mail(
        get_option( 'admin_email' ),
        'Klarna payment pending review',
        'Order #' . $order->get_order_number() . ' is pending Klarna fraud review.'
    );
}
add_action( 'wc_klarna_payments_pending', 'mytheme_klarna_payment_pending', 10, 2 );

wc_klarna_pending

An alias for wc_klarna_payments_pending. Both hooks fire at the exact same moment with the same arguments.

Signature

do_action( 'wc_klarna_pending', $order_id, $response );
  • int $order_id — The WooCommerce order ID.
  • array $response — The full decoded response from Klarna’s place-order API call.

When a Klarna payment is rejected

wc_klarna_payments_rejected

Fired when a Klarna payment is rejected or declined. Klarna does not provide the reason for rejection. The order status is updated (to failed by default, filterable via kp_order_rejected_status) before this action fires.

See also: wc_klarna_rejected below — an alias that fires at the same time.

Timing

  1. When the order is placed on the checkout page and Klarna returns a REJECTED fraud status — typically when the customer clicks the “Pay” button.
  2. Conditionally via a server-to-server callback if the WooCommerce order was not properly processed (e.g., the customer was not redirected to the thank-you page).

Signature

do_action( 'wc_klarna_payments_rejected', $order_id, $response );
  • int $order_id — The WooCommerce order ID.
  • array $response — The full decoded response from Klarna’s place-order API call.

Example

/**
 * Add an order note when a Klarna payment is rejected.
 *
 * @param int   $order_id The WooCommerce order ID.
 * @param array $response The Klarna API response.
 */
function mytheme_klarna_payment_rejected( $order_id, $response ) {
    $order = wc_get_order( $order_id );
    $order->add_order_note( 'Payment was rejected by Klarna.' );
}
add_action( 'wc_klarna_payments_rejected', 'mytheme_klarna_payment_rejected', 10, 2 );

wc_klarna_rejected

An alias for wc_klarna_payments_rejected. Both hooks fire at the exact same moment with the same arguments.

Timing

  1. When the order is placed on the checkout page. This is typically when the customer clicks the “Pay” button.
  2. Conditionally on whether the WooCommerce order was processed — a server-to-server callback will happen after the Klarna order was attempted if the WooCommerce order was not properly processed (e.g., the customer was not redirected to the thank-you page).

Signature

do_action( 'wc_klarna_rejected', $order_id, $response );
  • int $order_id — The WooCommerce order ID.
  • array $response — The full decoded response from Klarna’s place-order API call.

Example

/**
 * Example of how to add an order note when an order is rejected by Klarna.
 *
 * @param int   $order_id The ID of the order that was rejected.
 * @param array $response The response from Klarna that led to the rejection.
 */
function custom_add_order_rejected_note( $order_id, $response ) {
    $order = wc_get_order( $order_id );
    $order->add_order_note( 'The order was rejected by Klarna' );
}
add_action( 'wc_klarna_rejected', 'custom_add_order_rejected_note', 10, 2 );

After the place-order request completes

kp_after_place_order

Fired immediately after the plugin sends a place-order request to the Klarna API — before the plugin inspects the fraud status or handles any errors. Fires regardless of whether the request succeeded or failed.

Timing

Fires inside KP_Api::place_order() after the HTTP request to Klarna’s /payments/v1/authorizations/{auth_token}/order endpoint completes.

Signature

do_action( 'kp_after_place_order', $response, $order_id, $auth_token );
  • array|WP_Error $response — The raw response from Klarna. Can be a WP_Error on request failure.
  • int $order_id — The WooCommerce order ID.
  • string $auth_token — The Klarna authorization token used for the request.

Example

/**
 * Log the raw Klarna response for debugging purposes.
 *
 * @param array|WP_Error $response   The Klarna API response.
 * @param int            $order_id   The WooCommerce order ID.
 * @param string         $auth_token The Klarna authorization token.
 */
function mytheme_log_klarna_place_order( $response, $order_id, $auth_token ) {
    if ( is_wp_error( $response ) ) {
        error_log( 'Klarna place_order failed for order ' . $order_id . ': ' . $response->get_error_message() );
    }
}
add_action( 'kp_after_place_order', 'mytheme_log_klarna_place_order', 10, 3 );

When Klarna sends a push notification

wc_klarna_notification_listener

Fired when Klarna sends a server-to-server push notification to the store. The plugin itself does not process these notifications — this action is the hook point for the Klarna Order Management (or custom code) to handle incoming callbacks.

Timing

Fires when Klarna calls the WooCommerce API endpoint woocommerce_api_wc_gateway_klarna_payments (i.e., ?wc-api=WC_Gateway_Klarna_Payments).

Signature

do_action( 'wc_klarna_notification_listener' );

No parameters are passed. Retrieve the notification payload from the request data yourself (e.g., via $_GET).

Example

/**
 * Handle Klarna push notifications for custom workflows.
 */
function mytheme_klarna_notification_listener() {
    $klarna_order_id = filter_input( INPUT_GET, 'klarna_order_id', FILTER_SANITIZE_SPECIAL_CHARS );
    if ( empty( $klarna_order_id ) ) {
        return;
    }
    // Custom handling...
}
add_action( 'wc_klarna_notification_listener', 'mytheme_klarna_notification_listener' );

After Klarna feature availability is loaded

kp_plugin_features_initialized

Fired once per request after the plugin has loaded its feature-availability data from the database. Use this to react to which Klarna features (Payments, OSM, KEC, SIWK, etc.) are available for the current merchant credentials.

Timing

Fires inside PluginFeatures::init_features(). It only fires once per request — subsequent calls to init_features() are skipped unless $force = true is passed.

Signature

do_action( 'kp_plugin_features_initialized', $features );
  • array $features — Associative array of feature identifiers mapped to their availability data. Keys correspond to constants defined in KrokedilKlarnaFeatures.

Example

/**
 * Conditionally load custom assets based on available Klarna features.
 *
 * @param array $features The feature availability data.
 */
function mytheme_after_klarna_features_init( $features ) {
    if ( ! empty( $features['klarna_payments']['availability'] ) ) {
        // Klarna Payments is available — do something.
    }
}
add_action( 'kp_plugin_features_initialized', 'mytheme_after_klarna_features_init' );

After a KEC payment expires or is canceled

kec_cancel_order

Fired when a Klarna Express Checkout (KEC) one-step payment expires or is canceled. At the time this action fires, the WooCommerce order has already been moved to cancelled status.

Timing

Fires inside KECOneStepIntegration::handle_expired_payment() when Klarna notifies the store that a KEC payment request has expired.

Signature

do_action( 'kec_cancel_order', $order, $interoperability_token, $interoperability_data, $state, $payload );
  • WC_Order $order — The WooCommerce order that was canceled.
  • string $interoperability_token — The Klarna interoperability token for the session.
  • array $interoperability_data — Interoperability data (empty array at the time of firing).
  • string $state — The Klarna payment state (e.g., EXPIRED).
  • array $payload — The full payload received from Klarna.

Example

/**
 * Restore stock when a KEC order expires.
 *
 * @param WC_Order $order                  The canceled WooCommerce order.
 * @param string   $interoperability_token The Klarna interoperability token.
 * @param array    $interoperability_data  Interoperability data.
 * @param string   $state                  The payment state from Klarna.
 * @param array    $payload                The full Klarna payload.
 */
function mytheme_kec_cancel_order( $order, $interoperability_token, $interoperability_data, $state, $payload ) {
    wc_increase_stock_levels( $order->get_id() );
}
add_action( 'kec_cancel_order', 'mytheme_kec_cancel_order', 10, 5 );

Add custom actions to the KOM metabox

kom_meta_action_options

Fired inside the Klarna Order Management metabox to render <option> elements inside the “Choose an action…” dropdown. Hook into this to add custom actions to the metabox.

Timing

Fires when the Order Management metabox renders its action dropdown — only when at least one action (capture, cancel, or sync) is set to manual mode in the plugin settings.

Signature

do_action( 'kom_meta_action_options', $order_id, $klarna_order, $actions );
  • int $order_id — The WooCommerce order ID.
  • object $klarna_order — The Klarna order object retrieved from the Klarna API.
  • array $actions — Associative array of enabled manual actions: capturecancelsyncany.

Example

/**
 * Add a custom "Send invoice" option to the KOM metabox actions dropdown.
 *
 * @param int    $order_id     The WooCommerce order ID.
 * @param object $klarna_order The Klarna order object.
 * @param array  $actions      The currently enabled actions.
 */
function mytheme_kom_add_invoice_action( $order_id, $klarna_order, $actions ) {
    echo '<option value="send_invoice">Send invoice</option>';
}
add_action( 'kom_meta_action_options', 'mytheme_kom_add_invoice_action', 10, 3 );

Add tooltip text for KOM metabox actions

kom_meta_action_tips

Fired inside the Klarna Order Management metabox to render descriptive tooltip text for the available actions in the actions dropdown. Output is escaped and displayed in a WooCommerce help-tip.

Timing

Fires when the Order Management metabox renders its action dropdown, immediately after kom_meta_action_options.

Signature

do_action( 'kom_meta_action_tips', $order_id, $klarna_order, $actions );
  • int $order_id — The WooCommerce order ID.
  • object $klarna_order — The Klarna order object.
  • array $actions — Associative array of enabled manual actions.

Example

/**
 * Add tooltip text for the custom "Send invoice" action.
 *
 * @param int    $order_id     The WooCommerce order ID.
 * @param object $klarna_order The Klarna order object.
 * @param array  $actions      The currently enabled actions.
 */
function mytheme_kom_invoice_tip( $order_id, $klarna_order, $actions ) {
    echo 'Send invoice: Email a PDF invoice to the customer.<br/>';
}
add_action( 'kom_meta_action_tips', 'mytheme_kom_invoice_tip', 10, 3 );

Add content when no KOM actions are available

kom_meta_no_actions

Fired inside the Klarna Order Management metabox when there are no manual actions available (i.e., all actions — capture, cancel, sync — are set to automatic). Use this to render custom content in place of the actions dropdown.

Signature

do_action( 'kom_meta_no_actions', $order_id, $klarna_order, $actions );
  • int $order_id — The WooCommerce order ID.
  • object $klarna_order — The Klarna order object.
  • array $actions — Associative array of actions (all will be false in this context).

Example

/**
 * Display a custom message when all KOM actions are automated.
 *
 * @param int    $order_id     The WooCommerce order ID.
 * @param object $klarna_order The Klarna order object.
 * @param array  $actions      The enabled actions array.
 */
function mytheme_kom_no_actions_message( $order_id, $klarna_order, $actions ) {
    echo '<li><em>All Klarna order management actions are automated.</em></li>';
}
add_action( 'kom_meta_no_actions', 'mytheme_kom_no_actions_message', 10, 3 );

Filters

Auto-capture orders

kp_wc_api_request_body_args

Very important:

Before using this snippet, you need to reach out to Klarna merchant support to confirm if you are allowed to use this functionality contractually. This has to do with risk assessments etc in terms of payment being captured before the item is even shipped.

The kp_wc_api_request_body_args snippet will auto-capture all paid orders directly. It will however skip the orders with virtual or downloadable products, as WooCommerce has already handled those.

Note: It will not change any order statuses.

add_filter( 'kp_wc_api_request_body_args', 'kp_change_set_auto_capture_to_true', 10, 2 );
function kp_change_set_auto_capture_to_true( $request_args, $order_id = null ) {
	$is_standard_checkout = is_checkout() && ! kp_is_order_pay_page();

	if ( ! $is_standard_checkout ) {

		if ( empty( $order_id ) ) {
			return $request_args;
		}

		$order = wc_get_order( $order_id );
		if ( empty( $order ) ) {
			return $request_args;
		}
	}

	foreach ( $request_args['order_lines'] as $line_item ) {
		if ( 'shipping_fee' === $line_item['type'] ) {
			continue;
		}

		$order_items = $is_standard_checkout ? WC()->cart->get_cart() : $order->get_items();

		foreach ( $order_items as $order_item ) {
			$product = $is_standard_checkout ? WC()->cart->get_cart_item( $order_item['key'] )['data'] : $order_item->get_product();

			if ( ! $product ) {
				continue;
			}

			/* If any of the products is non-virtual AND downloadable product, enable auto-capture as these orders won't be automatically captured by WC. */
			if ( $line_item['name'] === $product->get_name() && ! ( $product->is_virtual() && $product->is_downloadable() ) ) {
				$request_args['auto_capture'] = true;
				return $request_args;
			}
		}
	}

	return $request_args;
}

Change the base region for API requests

klarna_base_region

If you have a European Merchant ID (MID) but also have “Global offering” enabled, Klarna Payments may allow USD as currency.
For Klarna Payments to work, the currency must match the country, meaning that you can’t have USD currency when the region, for example, is Europe.

This filter, where the region can be manually selected, fixes this issue.

/**
 * This filter lets you change the base region for API requests. Possible values:
 * - Europe             → '' (leave empty)
 * - North America      → '-na'
 * - Oceania            → '-oc'
 *
 * Default: ''
 */
add_filter(
	'klarna_base_region',
	function ( $region ) {
		return '-na';
	}
);

Change the purchase country sent to Klarna

wc_klarna_payments_country

Filters the purchase country sent to Klarna. The country is resolved from: (1) the WooCommerce order’s billing country, (2) the customer’s selected billing country on checkout, or (3) the store’s base location — in that order of priority.

Signature

apply_filters( 'wc_klarna_payments_country', $country );
  • string $country — The two-letter ISO 3166-1 alpha-2 country code (e.g., SEDEUS).

Example

/**
 * Override the Klarna purchase country.
 *
 * @param string $country The resolved country code.
 * @return string
 */
function mytheme_kp_override_country( $country ) {
    return $country;
}
add_filter( 'wc_klarna_payments_country', 'mytheme_kp_override_country' );

Change the Klarna logo in the Blocks checkout

kp_blocks_logo

Filters the URL of the Klarna logo displayed in the WooCommerce Blocks checkout. Defaults to the SVG logo bundled with the plugin.

Signature

apply_filters( 'kp_blocks_logo', $logo_url );
  • string $logo_url — The absolute URL to the logo image.

Example

/**
 * Replace the Klarna logo with a custom branded version.
 *
 * @param string $logo_url The current logo URL.
 * @return string
 */
function mytheme_kp_custom_logo( $logo_url ) {
    return 'https://example.com/my-klarna-logo.svg';
}
add_filter( 'kp_blocks_logo', 'mytheme_kp_custom_logo' );

Change the environment label in the KOM metabox

kom_meta_environment

Filters the environment string displayed in the Klarna Order Management metabox. The raw value is live or test.

Signature

apply_filters( 'kom_meta_environment', $environment );
  • string $environment — The environment value (livetest, or empty string).

Example

/**
 * Display a custom environment label in the KOM metabox.
 *
 * @param string $environment The environment value.
 * @return string
 */
function mytheme_kom_meta_environment( $environment ) {
    return 'live' === $environment ? 'Production' : 'Sandbox';
}
add_filter( 'kom_meta_environment', 'mytheme_kom_meta_environment' );

Change the order status label in the KOM metabox

kom_meta_order_status

Filters the Klarna order status string displayed in the Klarna Order Management metabox (e.g., AUTHORIZED, CAPTURED, CANCELLED).

Signature

apply_filters( 'kom_meta_order_status', $status );
  • string $status — The Klarna order status string.

Example

/**
 * Translate Klarna order status to a human-readable label.
 *
 * @param string $status The Klarna order status.
 * @return string
 */
function mytheme_kom_meta_order_status( $status ) {
    $labels = array(
        'AUTHORIZED'    => 'Authorized',
        'CAPTURED'      => 'Captured',
        'PART_CAPTURED' => 'Partially Captured',
        'CANCELLED'     => 'Cancelled',
    );
    return $labels[ $status ] ?? $status;
}
add_filter( 'kom_meta_order_status', 'mytheme_kom_meta_order_status' );

Change the payment method label in the KOM metabox

kom_meta_payment_method

Filters the initial payment method description displayed in the Klarna Order Management metabox (e.g., Pay Later, Pay Now, Financing).

Signature

apply_filters( 'kom_meta_payment_method', $payment_method );
  • string $payment_method — The payment method description from the Klarna order object.

Example

/**
 * Shorten the payment method label in the KOM metabox.
 *
 * @param string $payment_method The payment method description.
 * @return string
 */
function mytheme_kom_meta_payment_method( $payment_method ) {
    return wp_trim_words( $payment_method, 3, '' );
}
add_filter( 'kom_meta_payment_method', 'mytheme_kom_meta_payment_method' );

Change the label on the WooCommerce pay button

kp_blocks_order_button_label

If you are using the WooCommerce Checkout block and want to change the label on the Pay button, you can use the kp_blocks_order_button_label filter.

This is hard-coded by default, but by changing the return value (in this example “Pay with Klarna”) you can set a label of your choosing.

function change_kp_order_button_label( $label ) {
	return 'Pay with Klarna';
}
add_filter('kp_blocks_order_button_label', 'change_kp_order_button_label');

Change the label on the WooCommerce pay button for free orders

kp_blocks_order_button_label_free

If you are using the WooCommerce Checkout block and want to change the label on the Pay button when the cart total is zero (free order), you can use the kp_blocks_order_button_label_free filter. The default value is Pay with Klarna (free).

Example

/**
 * Customize the Klarna button label for free orders.
 *
 * @param string $label The current label.
 * @return string
 */
function mytheme_kp_free_button_label( $label ) {
    return __( 'Place Free Order via Klarna', 'my-plugin' );
}
add_filter( 'kp_blocks_order_button_label_free', 'mytheme_kp_free_button_label' );

Change the Klarna Web SDK client ID

kp_websdk_data_client_id

Filters the data-client-id attribute value injected into the Klarna Web SDK v1 (api.js) script tag. This is the public client ID used by the Klarna JavaScript SDK to initialize the payment widget.

Signature

apply_filters( 'kp_websdk_data_client_id', $client_id );
  • string $client_id — The Klarna client ID (e.g., klarna_live_client_xxx).

Example

/**
 * Override the Klarna Web SDK client ID.
 *
 * @param string $client_id The current client ID.
 * @return string
 */
function mytheme_kp_override_client_id( $client_id ) {
    return 'klarna_live_client_my_custom_id';
}
add_filter( 'kp_websdk_data_client_id', 'mytheme_kp_override_client_id' );

Disable lookup of orders sharing a Klarna transaction ID

kom_skip_matching_reference_orders

Controls whether the Order Management metabox queries and displays other WooCommerce orders that share the same Klarna transaction ID. Return true to skip this query — useful for performance on high-volume stores.

Signature

apply_filters( 'kom_skip_matching_reference_orders', $skip );
  • bool $skip — Whether to skip the duplicate-reference order lookup. Default: false.

Example

/**
 * Disable matching reference order lookup for better performance.
 *
 * @param bool $skip Whether to skip the lookup.
 * @return bool
 */
function mytheme_kom_skip_reference_orders( $skip ) {
    return true;
}
add_filter( 'kom_skip_matching_reference_orders', 'mytheme_kom_skip_reference_orders' );

Enable the Klarna Express Checkout button

kp_enable_express_button

Controls whether the Klarna Express Checkout (Express Button) feature is enabled. Defaults to false. The express button will not be enqueued, rendered, or loaded unless a filter callback returns true.

Signature

apply_filters( 'kp_enable_express_button', $enabled );
  • bool $enabled — Whether the express button is enabled. Default: false.

Example

/**
 * Enable the Klarna Express Checkout button.
 *
 * @param bool $enabled Whether the express button is enabled.
 * @return bool
 */
function mytheme_enable_kp_express_button( $enabled ) {
    return true;
}
add_filter( 'kp_enable_express_button', 'mytheme_enable_kp_express_button' );

Inspect the return fees applied to a Klarna refund

klarna_applied_return_fees

Filters the return fee data that was applied as part of a Klarna refund. Used after a refund request completes to retrieve any return fee included in the request. Also used internally to accumulate return fees during the refund process.

Signature

apply_filters( 'klarna_applied_return_fees', $fees );
  • array $fees — Array of applied return fees. Default: []. When fees are present, contains amount and tax_amount keys.

Example

/**
 * Log return fees applied during a Klarna refund.
 *
 * @param array $fees The applied return fees.
 * @return array
 */
function mytheme_log_klarna_return_fees( $fees ) {
    if ( ! empty( $fees ) ) {
        error_log( 'Klarna return fee applied: ' . wp_json_encode( $fees ) );
    }
    return $fees;
}
add_filter( 'klarna_applied_return_fees', 'mytheme_log_klarna_return_fees' );

Modify the Klarna Web SDK v1 script attributes

kp_websdk_v1_data_attributes

Filters the HTML attributes added to the Klarna Web SDK v1 (klarna_websdk_v1) script tag. Each key-value pair in the returned array becomes an HTML attribute. A null value adds the key as a boolean attribute (e.g., defer).

Signature

apply_filters( 'kp_websdk_v1_data_attributes', $attributes );
  • array $attributes — Associative array of attribute name → value pairs. Default: [ 'defer' => null ].

Example

/**
 * Add a crossorigin attribute to the Klarna Web SDK v1 script.
 *
 * @param array $attributes The current attributes.
 * @return array
 */
function mytheme_kp_websdk_v1_attrs( $attributes ) {
    $attributes['crossorigin'] = 'anonymous';
    return $attributes;
}
add_filter( 'kp_websdk_v1_data_attributes', 'mytheme_kp_websdk_v1_attrs' );

Modify the Klarna Web SDK v2 script attributes

kp_websdk_v2_data_attributes

Filters the HTML attributes added to the Klarna Web SDK v2 (klarna.mjs) script module tag. Equivalent to kp_websdk_v1_data_attributes but for the v2 module.

Signature

apply_filters( 'kp_websdk_v2_data_attributes', $attributes );
  • array $attributes — Associative array of attribute name → value pairs. Default: [ 'defer' => null ].

Example

/**
 * Remove the default "defer" attribute from the Klarna Web SDK v2 module.
 *
 * @param array $attributes The current attributes.
 * @return array
 */
function mytheme_kp_websdk_v2_no_defer( $attributes ) {
    unset( $attributes['defer'] );
    return $attributes;
}
add_filter( 'kp_websdk_v2_data_attributes', 'mytheme_kp_websdk_v2_no_defer' );

Change the order status for rejected payments

kp_order_rejected_status

Filters the WooCommerce order status applied to an order when Klarna rejects the payment. Defaults to failed.

Signature

apply_filters( 'kp_order_rejected_status', $status );
  • string $status — The WooCommerce order status slug (without the wc- prefix). Default: failed.

Example

/**
 * Set rejected Klarna orders to "cancelled" instead of "failed".
 *
 * @param string $status The default order status for rejected payments.
 * @return string
 */
function mytheme_kp_rejected_status( $status ) {
    return 'cancelled';
}
add_filter( 'kp_order_rejected_status', 'mytheme_kp_rejected_status' );

Change the product type for refunds of missing products

kom_line_item_product_type

Filters the Klarna line item type for refund order lines as a fallback when the WooCommerce product no longer exists (e.g., deleted products). When the product is available, the type is determined automatically from is_downloadable() / is_virtual().

Signature

apply_filters( 'kom_line_item_product_type', $type, $item );
  • string $type — The Klarna product type. Default: physical. Valid values: physicaldigital.
  • WC_Order_Item_Product $item — The WooCommerce order item being refunded.

Example

/**
 * Mark all items in a specific category as digital for Klarna refunds.
 *
 * @param string                $type The Klarna product type.
 * @param WC_Order_Item_Product $item The order item.
 * @return string
 */
function mytheme_kom_product_type( $type, $item ) {
    if ( has_term( 'digital-downloads', 'product_cat', $item->get_product_id() ) ) {
        return 'digital';
    }
    return $type;
}
add_filter( 'kom_line_item_product_type', 'mytheme_kom_product_type', 10, 2 );

Disable display of scheduled actions in the Order Management metabox

kom_skip_scheduled_actions

With the kom_skip_scheduled_actions filter, you can disable the display of scheduled actions in the Order Management metabox, on the admin order page.

add_filter( 'kom_skip_scheduled_actions', '__return_true' );

Disable Klarna Payments for subscriptions

wc_klarna_payments_supports

It is not possible to disable subscriptions in the Klarna account for Klarna Payments. If you want to disable Klarna Payments as a payment method for subscriptions, you can use the wc_klarna_payments_supports filter to remove subscriptions support from Klarna Payments.

 * Remove subscriptions support from Klarna Payments.
 *
 * @param array $supports The supported features.
 * @return array The filtered supported features.
 */
add_filter(
    'wc_klarna_payments_supports',
    function ( $supports ) {
        $subscriptions_support = array(
            'subscriptions',
            'subscription_cancellation',
            'subscription_suspension',
            'subscription_reactivation',
            'subscription_amount_changes',
            'subscription_date_changes',
            'subscription_payment_method_change',
            'subscription_payment_method_change_customer',
            'subscription_payment_method_change_admin',
            'multiple_subscriptions',
        );

        foreach ( $subscriptions_support as $subscription_support ) {
            $key = array_search( $subscription_support, $supports, true );
            if ( $key !== false ) {
                unset( $supports[ $key ] );
            }
        }

        return $supports;
    }
);

Force locale to a specific country and language

kp_locale

The Klarna plugin uses the WordPress function get_locale() to set the locale. With this snippet, you can force a specific country and language, American English in the example below.

Locales should be formatted as a language tag consisting of a two-letter language code combined with a two-letter country code according to RFC 1766. Examples are en-us for US English, en-gb for British English and sv-se for Swedish (in Sweden).

Countries are handled as two-letter country codes according to ISO 3166 alpha-2. Examples are us for the United States, gb for Great Britain and se for Sweden.

You can also find more Klarna-specific info in their API reference for data types.

/* Force English, US locale. */
add_filter(
	'kp_locale',
	function( $locale ) {
		return 'en-US';
	}
);

The following values are applicable:

AT: “de-AT”, “de-DE”, “en-DE”
BE: “be-BE”, “nl-BE”, “fr-BE”, “en-BE”
CH: “it-CH”, “de-CH”, “fr-CH”, “en-CH”
DE: “de-DE”, “de-AT”, “en-DE”
DK: “da-DK”, “en-DK”
ES: “es-ES”, “ca-ES”, “en-ES”
FI: “fi-FI”, “sv-FI”, “en-FI”
GB: “en-GB”
IT: “it-IT”, “en-IT”
NL: “nl-NL”, “en-NL”
NO: “nb-NO”, “en-NO”
PL: “pl-PL”, “en-PL”
SE: “sv-SE”, “en-SE”
US: “en-US”.

Force Express Button to a specific country and language

kp_express_button_locale

Filters the locale passed to the data-locale attribute of the <klarna-express-button> web component. Defaults to the value returned by kp_get_locale().

Signature

apply_filters( 'kp_express_button_locale', $locale );
  • string $locale — The locale string (e.g., en-USde-DE).

Example

/**
 * Force the express button to use English regardless of site locale.
 *
 * @param string $locale The current locale.
 * @return string
 */
function mytheme_kp_express_button_locale( $locale ) {
    return 'en-US';
}
add_filter( 'kp_express_button_locale', 'mytheme_kp_express_button_locale' );

Handle Klarna refunds with custom code

wc_klarna_payments_process_refund

Filters the result of Klarna Payments’ process_refund() method. The plugin itself does not process refunds — it returns false by default and delegates to the Klarna Order Management (or custom code) via this filter.

Signature

apply_filters( 'wc_klarna_payments_process_refund', $result, $order_id, $amount, $reason );
  • bool $result — Whether the refund was successfully processed. Default: false.
  • int $order_id — The WooCommerce order ID.
  • float|null $amount — The refund amount. null for a full refund.
  • string $reason — The reason for the refund.

Example

/**
 * Handle Klarna refunds with a custom integration.
 *
 * @param bool       $result   Whether the refund was processed.
 * @param int        $order_id The WooCommerce order ID.
 * @param float|null $amount   The refund amount.
 * @param string     $reason   The refund reason.
 * @return bool
 */
function mytheme_kp_process_refund( $result, $order_id, $amount, $reason ) {
    $success = my_refund_api( $order_id, $amount, $reason );
    return $success;
}
add_filter( 'wc_klarna_payments_process_refund', 'mytheme_kp_process_refund', 10, 4 );

Mixed payment scenarios

buy_and_default_tokenize

The buy_and_default_tokenize intent is designed for mixed payment scenarios – where an order includes both a one-time high-value purchase and a recurring low-value subscription. A common example is a piece of training equipment (one-time purchase) bundled with a monthly subscription (recurring payment) of supplements.

When using buy_and_default_tokenize, only the recurring portion of the order is tokenized using the pay_now payment method. The initial high-value item can be paid for using financing options (from the pay_over_time category). Without explicitly setting the intent to buy_and_default_tokenize, the financing option should still be available, but no recurring token would be created.

/**
 * Set the purchase intent.
 *
 * @param array $request The Klarna request.
 * @return array
 */
function merchant_kp_set_purchase_intent( $request ) {
	$body = json_decode( $request['body'], true );

	$body['intent'] = 'buy';
	if ( self::cart_has_subscription() ) {
		$body['intent'] = 'buy_and_default_tokenize';
	}

	$request['body'] = wp_json_encode( $body );
	return $request;
}


add_filter( 'wc_klarna_payments_create_session_args', 'merchant_kp_set_purchase_intent' );
add_filter( 'wc_klarna_payments_place_order_args', 'merchant_kp_set_purchase_intent' );
add_filter( 'wc_klarna_payments_create_customer_token_args', 'merchant_kp_set_purchase_intent' );
add_filter( 'wc_klarna_payments_update_session_args', 'merchant_kp_set_purchase_intent' );

Modify order & cart data sent to Klarna

kp_wc_api_request_args

Used to modify the order data that is sent to Klarna. In this example, the product names are anonymized.

add_filter(
	'kp_wc_api_request_args',
	function( $request_args ) {
		foreach ( $request_args['order_lines'] as $index => $order_line ) {
			if ( ! isset( $order_line['type'] ) ) {
				$request_args['order_lines'][ $index ]['name'] = md5( $order_line['name'] );
			}
		}
		return $request_args;
	}
);

As a result, 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 that the name is anonymized/censored.

Modify the available Klarna payment categories

wc_klarna_payments_available_payment_categories

Filters the list of Klarna payment categories (e.g., Pay Later, Pay Now, Financing) displayed on the checkout page. Each category becomes a separate payment option in the WooCommerce checkout.

Signature

apply_filters( 'wc_klarna_payments_available_payment_categories', $klarna_payment_categories );
  • array $klarna_payment_categories — Array of payment category objects/arrays from the Klarna session. Each entry contains identifiername, and asset_urls.

Example

/**
 * Remove the "Pay Later" category from the Klarna checkout options.
 *
 * @param array $categories The available Klarna payment categories.
 * @return array
 */
function mytheme_kp_remove_pay_later( $categories ) {
    return array_filter( $categories, function( $category ) {
        $id = is_array( $category ) ? $category['identifier'] : $category->identifier;
        return 'pay_later' !== $id;
    } );
}
add_filter( 'wc_klarna_payments_available_payment_categories', 'mytheme_kp_remove_pay_later' );

Modify the customer object for Klarna Payments

kp_get_customer_type

This filter allows you to customize the customer object before it is sent to Klarna, adding support for both B2C and B2B customers in the same store.

/**
 * Modify the customer object for Klarna Payments.
 * This filter allows you to customize the customer object before it is sent to Klarna.
 */
add_filter(
    'kp_get_customer_type',
    function ( $customer, $customer_type ) {

        if ( 'b2b' === $customer_type ) {
            // Modify the customer object as needed for B2B.
        }

        return $customer;
    },
    10,
    2
);

Modify the Klarna customer type (B2C/B2B)

klarna_get_customer_type

Some merchants may need to support both B2C and B2B customers in the same store. By default, the plugin sends a single customer type to Klarna, but this filter allows merchants to dynamically modify the customer type before the request is made.

Using the klarna_get_customer_type filter, you can programmatically determine whether a customer should be treated as B2C or B2B. This can be useful if the customer type depends on specific checkout data, stored customer metadata, or custom checkout logic.

For example, a store might treat customers as B2B if a VAT number is present, while all other customers are treated as B2C.

The example below demonstrates how to modify the customer type based on whether the customer has a VAT number saved in their WooCommerce customer meta.

/**
 * Modify the customer type for Klarna.
 *
 * @param string $customer_type The current customer type.
 * @return string The modified customer type.
 */
function klarna_modify_customer_type( $customer_type ) {
	// If the customer has a vat number stored, treat them as a B2B customer.
	$vat_number = WC()->customer ? trim( (string) WC()->customer->get_meta( 'vat_number' ) ) : '';
	if ( ! empty( $vat_number ) ) {
		return 'b2b';
	}

	return $customer_type;
}
add_filter( 'klarna_get_customer_type', 'klarna_modify_customer_type' );

Modify the Klarna API request arguments

wc_klarna_payments_request_args

Filters the complete HTTP request arguments array (headers, method, timeout, body) for every Klarna Payments API request (GET, POST, and PATCH). This is the lowest-level request filter — applied after all body filters.

Signature

apply_filters( 'wc_klarna_payments_request_args', $args );
  • array $args — The full wp_remote_* arguments array, including headersuser-agentmethodtimeout, and optionally body.

Example

/**
 * Add a custom header to all Klarna API requests.
 *
 * @param array $args The HTTP request arguments.
 * @return array
 */
function mytheme_kp_add_custom_header( $args ) {
    $args['headers']['X-My-Plugin-Version'] = MY_PLUGIN_VERSION;
    return $args;
}
add_filter( 'wc_klarna_payments_request_args', 'mytheme_kp_add_custom_header' );

Modify the Klarna Payments settings fields

wc_gateway_klarna_payments_settings

Filters the full array of settings fields rendered on the Klarna Payments settings page in WooCommerce → Settings → Payments. Use this to add, modify, or remove settings fields.

Signature

apply_filters( 'wc_gateway_klarna_payments_settings', $form_fields );
  • array $form_fields — The WooCommerce settings form fields array.

Example

/**
 * Add a custom text field to the Klarna Payments settings page.
 *
 * @param array $fields The current settings fields.
 * @return array
 */
function mytheme_add_kp_custom_setting( $fields ) {
    $fields['my_custom_setting'] = array(
        'title'   => __( 'My Custom Setting', 'my-plugin' ),
        'type'    => 'text',
        'default' => '',
    );
    return $fields;
}
add_filter( 'wc_gateway_klarna_payments_settings', 'mytheme_add_kp_custom_setting' );

Modify the parameters passed to the Klarna Payments frontend

wc_kp_checkout_params

Filters the JavaScript parameters object (klarna_payments_params) localized to the checkout page script. This is the primary filter for modifying any data passed from PHP to the frontend Klarna Payments JavaScript.

Signature

apply_filters( 'wc_kp_checkout_params', $params );
  • array $params — Associative array of parameters. Includes AJAX URLs, nonces, cart total, testmode flag, customer type, client token, and i18n strings.

Example

/**
 * Pass a custom param to the Klarna Payments frontend script.
 *
 * @param array $params The checkout script params.
 * @return array
 */
function mytheme_kp_checkout_params( $params ) {
    $params['my_custom_flag'] = get_option( 'my_plugin_feature_enabled', 'no' );
    return $params;
}
add_filter( 'wc_kp_checkout_params', 'mytheme_kp_checkout_params' );

Modify the request timeout time

wc_kp_request_timeout

Modify the timeout time for all HTTP requests sent to Klarna (measured in seconds). Default is 10 seconds.

/**
 * Filter hook wc_kp_request_timeout
 * Modify the timeout time used for HTTP requests sent to Klarna.
 */
add_filter( 'wc_kp_request_timeout', 'custom_wc_kp_request_timeout' );
function custom_wc_kp_request_timeout( $time ) {
    return 20;
}

Modify the Order Management request timeout

kom_request_timeout

Filters the HTTP timeout (in seconds) for Klarna Order Management API requests (capture, refund, cancel, update). This is separate from wc_kp_request_timeout which applies to payment session requests.

Signature

apply_filters( 'kom_request_timeout', $timeout );
  • int $timeout — The timeout in seconds. Default: 10.

Example

/**
 * Increase the Order Management API timeout.
 *
 * @param int $timeout The current timeout.
 * @return int
 */
function mytheme_kom_request_timeout( $timeout ) {
    return 30;
}
add_filter( 'kom_request_timeout', 'mytheme_kom_request_timeout' );

Modify the order statuses that allow Klarna order updates

kom_allowed_update_statuses

Filters the list of WooCommerce order statuses for which an automatic Klarna order update (syncing order lines with Klarna) is permitted when an order is edited in the admin.

Signature

apply_filters( 'kom_allowed_update_statuses', $statuses );
  • array $statuses — Array of WooCommerce order status slugs (without wc- prefix). Default: [ 'on-hold' ].

Example

/**
 * Also allow order line updates for pending orders.
 *
 * @param array $statuses The allowed statuses.
 * @return array
 */
function mytheme_kom_allowed_statuses( $statuses ) {
    $statuses[] = 'pending';
    return $statuses;
}
add_filter( 'kom_allowed_update_statuses', 'mytheme_kom_allowed_statuses' );

Modify the Klarna order update request

kom_order_update_args

Filters the request body sent to Klarna when updating order lines via the Order Management API — e.g., when an admin edits an order and the plugin syncs the changes.

Signature

apply_filters( 'kom_order_update_args', $data, $order_id );
  • array $data — The request body containing order_linesorder_amount, and order_tax_amount.
  • int $order_id — The WooCommerce order ID.

Example

/**
 * Add a merchant reference to Klarna order update requests.
 *
 * @param array $data     The order update request body.
 * @param int   $order_id The WooCommerce order ID.
 * @return array
 */
function mytheme_kom_order_update_args( $data, $order_id ) {
    $data['merchant_reference1'] = 'REF-' . $order_id;
    return $data;
}
add_filter( 'kom_order_update_args', 'mytheme_kom_order_update_args', 10, 2 );

Modify the Klarna order capture request

kom_order_capture_args

Filters the request body sent to Klarna when capturing an order via the Order Management API. Useful for customizing the captured amount or appending shipping tracking information.

Signature

apply_filters( 'kom_order_capture_args', $data, $order_id );
  • array $data — The capture request body. Contains captured_amount and optionally order_lines.
  • int $order_id — The WooCommerce order ID.

Example

/**
 * Add a shipping tracking number to Klarna capture requests.
 *
 * @param array $data     The capture request body.
 * @param int   $order_id The WooCommerce order ID.
 * @return array
 */
function mytheme_kom_capture_args( $data, $order_id ) {
    $order = wc_get_order( $order_id );
    $tracking = $order->get_meta( '_tracking_number' );
    if ( $tracking ) {
        $data['shipping_info'] = array(
            array( 'tracking_number' => $tracking ),
        );
    }
    return $data;
}
add_filter( 'kom_order_capture_args', 'mytheme_kom_capture_args', 10, 2 );

Modify the Klarna order refund request

kom_refund_order_args

Filters the order lines array sent to Klarna when processing a refund via the Order Management API. Called at the end of RequestPostRefund::get_refund_order_lines() with the fully assembled refund lines.

Signature

apply_filters( 'kom_refund_order_args', $data, $order_id );
  • array $data — The refund order lines array. Each entry contains typereferencenamequantityunit_pricetax_ratetotal_amounttotal_discount_amount, and total_tax_amount.
  • int $order_id — The WooCommerce order ID.

Example

/**
 * Modify refund order lines before sending to Klarna.
 *
 * @param array $data     The refund order lines.
 * @param int   $order_id The WooCommerce order ID.
 * @return array
 */
function mytheme_kom_refund_args( $data, $order_id ) {
    // Inspect or modify $data order lines here.
    return $data;
}
add_filter( 'kom_refund_order_args', 'mytheme_kom_refund_args', 10, 2 );

Register a custom Klarna REST API controller

klarna_register_api_controller

Filters the array of REST API controller objects registered by the Klarna Payments plugin. Controllers must extend KrokedilKlarnaApiControllersController. Use this to add custom REST API endpoints within the plugin’s REST API namespace.

Signature

apply_filters( 'klarna_register_api_controller', $controllers );
  • array $controllers — Array of controller instances. Default: [].

Example

use KrokedilKlarnaApiControllersController;

class My_Custom_Klarna_Controller extends Controller {
    public function register_routes() {
        register_rest_route( 'klarna/v1', '/my-endpoint', array(
            'methods'  => 'GET',
            'callback' => array( $this, 'handle' ),
        ) );
    }
    public function handle( $request ) {
        return rest_ensure_response( array( 'ok' => true ) );
    }
}

/**
 * Register a custom Klarna REST API controller.
 *
 * @param array $controllers The current controllers.
 * @return array
 */
function mytheme_register_klarna_controller( $controllers ) {
    $controllers[] = new My_Custom_Klarna_Controller();
    return $controllers;
}
add_filter( 'klarna_register_api_controller', 'mytheme_register_klarna_controller' );

Remove postcode spaces

wc_kp_remove_postcode_spaces

Controls whether spaces are stripped from postal codes before they are sent to Klarna. Return true to preserve spaces; the default false means the plugin strips them.

Signature

apply_filters( 'wc_kp_remove_postcode_spaces', $preserve );
  • bool $preserve — Whether to preserve spaces in postcodes. Default: false (spaces are stripped).

Example

/**
 * Preserve postcode spaces for UK customers.
 *
 * @param bool $preserve Whether to preserve spaces.
 * @return bool
 */
function mytheme_kp_keep_postcode_spaces( $preserve ) {
    $country = WC()->customer ? WC()->customer->get_billing_country() : '';
    return 'GB' === $country ? true : $preserve;
}
add_filter( 'wc_kp_remove_postcode_spaces', 'mytheme_kp_keep_postcode_spaces' );
On this page:
  1. How and where to insert the code?
  2. Actions
  3. Filters

Jump to categories