Chris Grant
Chris Grant

Reputation: 1

Display product variations in WooCommerce Hand-picked Products block

I'm attempting to show the product variations of products while using the woocommerce Hand-picked Products block.

For the shop and archive pages this solution works fine.

How to add variation selection in Woo commerce to the Products Archive page?

However I'm struggling to get the variations to show using the woocommerce blocks.

/**
 * Display product variations in WooCommerce Hand-picked Products block.
 *
 * @param array $attributes Block attributes.
 * @param string $content Block content.
 * @return string
 */
function custom_display_product_variations_in_handpicked_block($attributes, $content) {
    // Check if the block is a Hand-picked Products block
    if ($attributes['name'] === 'woocommerce/handpicked-products') {

        // Get the list of hand-picked product IDs
        $product_ids = ! empty($attributes['products']) ? $attributes['products'] : array();

        if (! empty($product_ids)) {
            $content .= '<ul class="product-variations-list">';

            foreach ($product_ids as $product_id) {
                // Get product variations
                $variations = wc_get_product_variations($product_id);

                if ($variations) {
                    foreach ($variations as $variation) {
                        $variation_id = $variation->get_id();
                        $variation_name = wc_get_formatted_variation($variation->get_variation_attributes(), true);
                        $variation_price = $variation->get_price_html();

                        // Display variation details
                        $content .= '<li>';
                        $content .= '<a href="' . esc_url(get_permalink($variation_id)) . '">' . esc_html($variation_name) . '</a>';
                        $content .= '<span class="variation-price">' . $variation_price . '</span>';
                        $content .= '</li>';
                    }
                }
            }

            $content .= '</ul>';
        }
    }

    return $content;
}

add_filter('render_block', 'custom_display_product_variations_in_handpicked_block', 10, 2);

Upvotes: 0

Views: 181

Answers (1)

Opicron
Opicron

Reputation: 16

Not a complete answer, but I was looking in sort of the same functionality. And the following helped me figure it out.

By utilizing the following hook: woocommerce_blocks_product_grid_item_html, you can change the actual product block inside of the handpicked-product block.

The hook takes three arguments: $html, $data, $product

How to override new Gutenberg product loop block markup

Upvotes: 0

Related Questions