Home / eCommerce / Add Wholesale Order Form Favourites Button Functionality To WooCommerce Single Product Pages
Duplicate Snippet

Embed Snippet on Your Site

Add Wholesale Order Form Favourites Button Functionality To WooCommerce Single Product Pages

Works hand in hand with the WooCommerce Wholesale Order Form plugin to provide product favouriting functionality on single product pages.

Code Preview
php
<?php
/**
 * Output scripts and styles for the favourites button in the head.
 */
function wwof_output_favourites_scripts() {
    // Only load on single product pages.
    if ( ! is_product() ) {
        return;
    }
    // Get current user ID.
    $user_id = get_current_user_id();
    // Only load for logged-in users.
    if ( ! $user_id ) {
        return;
    }
    // At wp_head, the global $product might not be set up yet.
    // So we need to get the product ID from the queried object.
    $product_id    = get_queried_object_id();
    $in_favourites = false;
    // If we have the helper class from WooCommerce Wholesale Order Form.
    if ( class_exists( '\RymeraWebCo\WWOF\Helpers\WWOF' ) ) {
        $favourites    = \RymeraWebCo\WWOF\Helpers\WWOF::get_favourite_products( $user_id );
        $in_favourites = in_array( $product_id, $favourites, true );
    }
    // CSS styles.
    echo '<style>
    .wwof-favourites-button-wrapper {
        margin: 1em 0;
    }
    
    .wwof-favourites-button {
        display: inline-flex !important;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 0.5em 1em;
        border-radius: 4px;
        transition: all 0.3s ease;
        background-color: #f8f8f8 !important;
        border: 1px solid #ddd !important;
        color: #333 !important;
    }
    
    .wwof-favourites-button:hover {
        background-color: #f0f0f0 !important;
    }
    
    .wwof-favourites-button .heart-icon {
        fill: #ccc;
        transition: fill 0.3s ease;
    }
    
    .wwof-favourites-button.in-favourites .heart-icon {
        fill: #e94057;
    }
    
    .wwof-favourites-button.in-favourites {
        background-color: #f9f3f4 !important;
        border-color: #e9b8b8 !important;
    }
    
    .wwof-favourites-button:disabled {
        opacity: 0.7;
        cursor: not-allowed;
    }
    </style>' . "\n";
    // JavaScript.
    ?>
    <script>
    jQuery(document).ready(function($) {
        const button = $('#wwof-favourites-button');
        const wwofFavourites = {
            apiUrl: '<?php echo esc_url_raw( rest_url( 'wwof/v3/favourites' ) ); ?>',
            nonce: '<?php echo esc_attr( wp_create_nonce( 'wp_rest' ) ); ?>',
            inFavourites: <?php echo $in_favourites ? 'true' : 'false'; ?>,
            productId: <?php echo esc_js( $product_id ); ?>,
            addText: '<?php echo esc_js( __( 'Add to Favourites', 'wwof-favourites-button' ) ); ?>',
            removeText: '<?php echo esc_js( __( 'Remove from Favourites', 'wwof-favourites-button' ) ); ?>',
            addedMessage: '<?php echo esc_js( __( 'Product saved to favourites.', 'wwof-favourites-button' ) ); ?>',
            removedMessage: '<?php echo esc_js( __( 'Product removed from favourites.', 'wwof-favourites-button' ) ); ?>',
            errorMessage: '<?php echo esc_js( __( 'Error updating favourites. Please try again.', 'wwof-favourites-button' ) ); ?>'
        };
        
        button.on('click', function(e) {
            e.preventDefault();
            const productId = $(this).data('product-id');
            const isInFavourites = $(this).hasClass('in-favourites');
            
            // Disable button during API call.
            button.prop('disabled', true);
            
            const endpoint = isInFavourites ? 
                `${wwofFavourites.apiUrl}/remove/${productId}` :
                `${wwofFavourites.apiUrl}/save/${productId}`;
            
            const method = isInFavourites ? 'DELETE' : 'POST';
            
            // Call API.
            $.ajax({
                url: endpoint,
                method: method,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', wwofFavourites.nonce);
                },
                success: function(response) {
                    // Toggle button class and text.
                    if (isInFavourites) {
                        button.removeClass('in-favourites');
                        $('.wwof-favourites-text', button).text(wwofFavourites.addText);
                        
                        // Show success message.
                        if (response.message) {
                            $('<div class="woocommerce-message" role="alert">' + response.message + '</div>')
                                .insertBefore('.product_title')
                                .delay(3000)
                                .fadeOut(400, function() { $(this).remove(); });
                        }
                    } else {
                        button.addClass('in-favourites');
                        $('.wwof-favourites-text', button).text(wwofFavourites.removeText);
                        
                        // Show success message.
                        if (response.message) {
                            $('<div class="woocommerce-message" role="alert">' + response.message + '</div>')
                                .insertBefore('.product_title')
                                .delay(3000)
                                .fadeOut(400, function() { $(this).remove(); });
                        }
                    }
                },
                error: function(xhr) {
                    console.error('Error updating favourites', xhr);
                    
                    // Show error message.
                    $('<div class="woocommerce-error" role="alert">' + wwofFavourites.errorMessage + '</div>')
                        .insertBefore('.product_title')
                        .delay(3000)
                        .fadeOut(400, function() { $(this).remove(); });
                },
                complete: function() {
                    // Re-enable button.
                    button.prop('disabled', false);
                }
            });
        });
    });
    </script>
    <?php
}
add_action( 'wp_head', 'wwof_output_favourites_scripts' );
/**
 * Add the favourites button to the single product page.
 */
function wwof_add_favourites_button() {
    global $product;
    // Only proceed if we have a product.
    if ( ! $product ) {
        return;
    }
    // Get current user ID.
    $user_id = get_current_user_id();
    // Only show for logged-in users.
    if ( ! $user_id ) {
        return;
    }
    // Check if this product is already in favourites.
    $product_id    = $product->get_id();
    $in_favourites = false;
    // If we have the helper class from WooCommerce Wholesale Order Form.
    if ( class_exists( '\RymeraWebCo\WWOF\Helpers\WWOF' ) ) {
        $favourites    = \RymeraWebCo\WWOF\Helpers\WWOF::get_favourite_products( $user_id );
        $in_favourites = in_array( $product_id, $favourites, true );
    }
    // Button HTML.
    ?>
    <div class="wwof-favourites-button-wrapper">
        <button type="button" id="wwof-favourites-button" class="button wwof-favourites-button <?php echo $in_favourites ? 'in-favourites' : ''; ?>" data-product-id="<?php echo esc_attr( $product_id ); ?>">
            <span class="wwof-favourites-icon">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" class="heart-icon" />
                </svg>
            </span>
            <span class="wwof-favourites-text">
                <?php echo $in_favourites ? esc_html__( 'Remove from Favourites', 'wwof-favourites-button' ) : esc_html__( 'Add to Favourites', 'wwof-favourites-button' ); ?>
            </span>
        </button>
    </div>
    <?php
}
// Hook to add our button after the add to cart button.
add_action( 'woocommerce_after_add_to_cart_button', 'wwof_add_favourites_button' );

Comments

Add a Comment