1

我为 Magento 创建了一个自定义选项图像切换器,脚本将下拉选项中的值与与产品相关的所有图像名称进行比较,并找到最相似的,您可以在此处查看示例

问题是如何将“选定”选项图像添加到购物车,或者更好地说明如何应用该图像而不是购物车中的默认缩略图?

无论如何,这是完整的代码 - 也许有人甚至会发现这部分很有用:)

<?php
// load all images related to product
$product = $this->getProduct();
$galleryData = $product->getData('media_gallery');


$images_array = array();
foreach ($galleryData['images'] as $image) {
 array_push($images_array, $image['file']);
}?>

<?php
$colour_select_id = '';
$custom_options_arr = array();
foreach ($_options as $_option) {
 if ($_option->getTitle() == 'Helmet Color/Design' || $_option->getTitle() == 'Color')  {
    $colour_select_id = 'select_' . $_option->getId();
    $values = $_option->getValues();
    foreach ($values as $value) {
        $current_option = ($value->getData());
        $custom_options_arr[$current_option['option_type_id']] = $current_option['title'];
    }
  }
}
// $custom_options_arr now holds key=>value pairs of option_type_id => title

$custom_images_to_output = array();
foreach ($custom_options_arr as $key => $value) {
$best_match = $images_array[0];
for ($i = 1; $i < count($images_array); $i++) {
    if (similar_text(strtoupper($images_array[$i]), strtoupper($value)) > similar_text(strtoupper($best_match), strtoupper($value))) {
        $best_match = $images_array[$i];
    }
}
$custom_images_to_output[$key] = $best_match;
}
$base_url = Mage::getBaseUrl('media') . 'catalog/product';
?>    

<?php if ($colour_select_id) { ?>

<script type="text/javascript">
    jQuery(document).ready(function() {

        var opt_object = <?php echo json_encode($custom_images_to_output); ?>;
        var base_path = '<?= $base_url;?>';

        jQuery("#<?= $colour_select_id ?>").change(function() {

            var optionValue = jQuery(this).attr('value');

            if (optionValue) {
                var optionValueText = jQuery.trim(jQuery('#<?= $colour_select_id ?> :selected').text());
                if (opt_object.hasOwnProperty(optionValue)) {
                    optionValueText = opt_object[optionValue];
                }

                jQuery("#image").fadeOut(function() { 
                  jQuery(this).load(function() { 
                  jQuery(this).fadeIn(); }); 
                  jQuery(this).attr("src", base_path + optionValueText);
                  jQuery('#image-zoom').attr("href", base_path + optionValueText);
                }); 

           }    
        });
    });
</script>
4

0 回答 0