Skip to content

Instantly share code, notes, and snippets.

@xlplugins
Created May 27, 2026 11:52
Show Gist options
  • Select an option

  • Save xlplugins/97f1f59f5ba1a8c34969fc4eb644e967 to your computer and use it in GitHub Desktop.

Select an option

Save xlplugins/97f1f59f5ba1a8c34969fc4eb644e967 to your computer and use it in GitHub Desktop.
Move Free Gift to Top
add_action( 'woocommerce_before_calculate_totals', function ( $cart ) {
if ( ! $cart instanceof WC_Cart || $cart->is_empty() ) {
return;
}
$contents = $cart->cart_contents;
if ( count( $contents ) < 2 ) {
return;
}
$rewards = [];
$rest = [];
foreach ( $contents as $key => $item ) {
$is_reward = ! empty( $item['_fkcart_free_gift'] );
if ( ! $is_reward && isset( $item['data'] ) && is_object( $item['data'] ) ) {
$price = (float) $item['data']->get_price();
if ( 0.0 === $price ) {
$is_reward = true;
}
}
if ( $is_reward ) {
$rewards[ $key ] = $item;
} else {
$rest[ $key ] = $item;
}
}
if ( empty( $rewards ) ) {
return;
}
$reordered = $rewards + $rest;
if ( array_keys( $reordered ) === array_keys( $contents ) ) {
return;
}
$cart->cart_contents = $reordered;
}, 99, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment