You are here

function commerce_wishlist_product_add in Commerce Wishlist 7.3

Add a product to a wish list.

Parameters

object $product: The product entity being added to the wish list.

object|null $wishlist: The wishlist it is being added to. Defaults to the user's primary wish list.

int|null $uid: The UID of the owner of the wish list. Defaults to the current user.

string $display_path: The display path to attach to the new line item. This can be used for linking the item to the original node that was shown when it was added.

Return value

bool|object FALSE if the product was not added, otherwise the new line item.

5 calls to commerce_wishlist_product_add()
CommerceWishlistTest::testCommerceWishlistSharing in ./commerce_wishlist.test
commerce_wishlist_add_form_submit in ./commerce_wishlist.module
Submit callback for commerce_cart_add_to_cart_form().
commerce_wishlist_product_add_ajax in ./commerce_wishlist.module
Page callback: Ajax product add.
commerce_wishlist_product_add_page in ./commerce_wishlist.module
Menu callback: Perform various actions (add to wishlist etc).
commerce_wishlist_user_login in ./commerce_wishlist.module
Implements hook_user_login().

File

./commerce_wishlist.module, line 945
Provides a wish list for use in Drupal Commerce.

Code

function commerce_wishlist_product_add($product, $wishlist = NULL, $uid = NULL, $display_path = '') {
  $line_item = commerce_product_line_item_new($product, 1);
  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
  $line_item_wrapper->commerce_display_path
    ->set($display_path);
  if ($uid === NULL) {
    global $user;
    $uid = $user->uid;
  }

  // First attempt to load the customer's shopping cart order.
  if ($wishlist === NULL) {
    $wishlist = commerce_wishlist_order_load($uid);
  }

  // If no wish list exists, create one now.
  if (empty($wishlist)) {
    $wishlist = commerce_wishlist_order_new($uid);
  }

  // Return if it's already in there.
  if (commerce_wishlist_user_has_product_in_wishlist($product->product_id, $uid)) {
    return FALSE;
  }

  // Set the incoming line item's order_id.
  $line_item->order_id = $wishlist->order_id;

  // Wrap the order for easy access to field data.
  $wishlist_wrapper = entity_metadata_wrapper('commerce_order', $wishlist);

  // Save the incoming line item now so we get its ID.
  commerce_line_item_save($line_item);

  // Add it to the order's line item reference value.
  $wishlist_wrapper->commerce_line_items[] = $line_item;

  // Save the updated order.
  commerce_order_save($wishlist);

  // Invoke the product add event with the newly saved or updated line item.
  rules_invoke_all('commerce_wishlist_product_add', $wishlist, $product, $line_item);

  // Return the line item.
  return $line_item;
}