Load additional product attributes in Wishlist

Where are the products loaded?
The products are loaded in the "_afterLoad" method of the items collection. A product collection is instantiated there based on the product ids of all items and directly loaded to assign the products to their wishlist items.

Unfortunately it is instantiated and loaded from within the same method, so it is not easily changed via plugin. The attributes to select are hard coded:

$attributesToSelect = [
      'name',
      'visibility',
      'small_image',
      'thumbnail',
      'links_purchased_separately',
      'links_title',
  ];

The method dispatches an event wishlist_item_collection_products_after_load, but unfortunately no "before load" event.

How can you specify the loaded attributes then?
You could replace the collection class, or write a plugin for the _assignProducts method that replaces the whole method.

But I found a better way: use a custom product collection factory that sets the attributes to select during creation.

These files go into a custom module Stack_Wishlist:

etc/frontend/di.xml



    
        
            \Stack\Wishlist\ResourceModel\ProductCollectionFactory
        
    

ResourceModel/ProductCollectionFactory.php

catalogConfig = $catalogConfig;
    }

    public function create(array $data = array())
    {
        $collection = parent::create($data);
        $collection->addAttributeToSelect($this->catalogConfig->getProductAttributes());
        return $collection;
    }
}

Here I add all attributes that are configured as "used in product listing", i.e. all that are present in the flat index tables. You could specify them manually instead as well.

你可能感兴趣的:(magento2)