Hiển thị nội dung khuyến mại tùy chọn sản phẩm trong WooCommerce


function gift_content() {
    global $post;
    
    // Retrieve product IDs from the options field.
    $product_ids = get_field('selected_products', 'option');
    $display_type = get_field('display_type', 'option');
    $list = get_field('display_list', 'option');
    $recommend = get_field('recommend', 'option');
    $content = '';

    // Check if there are any products.
    if ($product_ids) {
        $content .= '<div class="content_gift">';
        $content .= '<div class="content_gift_title">Promotion (1 of 2)</div>';
        $content .= '<div class="content_gift_item">';
        
        // Process the products.
        $first = reset($product_ids);
        foreach ($product_ids as $pid) {
            $checked = ($pid === $first) ? 'checked' : '';
            $product = wc_get_product($pid);
            $link = get_the_permalink($pid);
            $check_gift = ($recommend == '0') ? '' : 'check_gift';
            
            $content .= '<div class="flex-custom">';
            $content .= '<input type="radio" class="check_gift" value="' . esc_attr(get_the_title($pid)) . '" name="' . esc_attr($check_gift) . '" id="check_gift' . esc_attr($pid) . '" ' . esc_attr($checked) . '>';
            $content .= '<label for="check_gift' . esc_attr($pid) . '" class="flex-custom">';
            $content .= '<div class="content_gift_img">' . get_the_post_thumbnail($pid) . '</div>';
            $content .= '<div class="content_gift_name">' . esc_html(get_the_title($pid)) . '</div>';
            $content .= '</label>';
            $content .= '</div>';
            wp_reset_postdata();
        }
        $content .= '</div>';
        $content .= '</div>';
    }

    // Check display conditions for the promotional content.
    if ($list) {
        $id_array = array_map('intval', $list);
        if ($display_type == 'lt' && !is_single($id_array)) {
            echo $content;
        }
        if ($display_type == 'dc' && is_single($id_array)) {
            echo $content;
        }
    }

    if ($display_type == 'tc') {
        echo $content;
    }
}

// Add promotional content before the "Add to Cart" button in WooCommerce.
add_action('woocommerce_before_add_to_cart_button', 'gift_content', 21);