Created
May 27, 2026 11:52
-
-
Save xlplugins/97f1f59f5ba1a8c34969fc4eb644e967 to your computer and use it in GitHub Desktop.
Move Free Gift to Top
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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