Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndreiTelteu/d306288fa8770228c3c16f79c7b5b245 to your computer and use it in GitHub Desktop.
Save AndreiTelteu/d306288fa8770228c3c16f79c7b5b245 to your computer and use it in GitHub Desktop.
WooCommerce make cart session functional inside an iframe .md

If you need your woocommerce cart functions to work while inside an iframe, you have to add this code in your theme's functions file (or plugin's function file):

function iframe_cookies_samesite_filter_wc_session($enabled, $name, $value, $expire, $secure)
{
    if ( ! headers_sent() ) {
        setcookie($name, $value, [
            'secure'   => true,
            'httponly' => apply_filters( 'woocommerce_cookie_httponly', $httponly, $name, $value, $expire, $secure ),
            'samesite' => 'None', // Cookies will be sent in all contexts
            //'samesite' => 'Lax', // play around with lax if "none" does not work
            'path'     => COOKIEPATH ? COOKIEPATH : '/',
            'expires'   => $expire,
            'domain'   => COOKIE_DOMAIN,
        ]);
    } elseif ( Constants::is_true( 'WP_DEBUG' ) ) {
        headers_sent( $file, $line );
        trigger_error( "{$name} cookie cannot be set - headers already sent by {$file} on line {$line}", E_USER_NOTICE ); // @codingStandardsIgnoreLine
    }
    return false;
}
add_filter('woocommerce_set_cookie_enabled', 'iframe_cookies_samesite_filter_wc_session', 10, 5 );

For the checkout page to work add this to the theme's functions file:

// REMOVE X-Frame-Options because ios does not work
remove_action('template_redirect', 'wc_send_frame_options_header');
remove_action('admin_init', 'send_frame_options_header');
remove_action('login_init', 'send_frame_options_header');
remove_action('init', 'send_frame_options_header');

Please beware payment processors don't usually work inside iframe because they include "X-Frame-Options" header for security reasons. You must redirect to the payment processor page with javascript:

if (window.location !== window.top.location) {
    window.top.location.href = location.href;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment