12

I fetch a specific product in a page that is outside of woocommerce template and I need to add the 'Add to cart' button. I looked at the code and I saw woocommerce doing it this way,

<a href="/?product_cat=icecream&amp;add-to-cart=77" rel="nofollow" data-product_id="77" data-product_sku="" class="button add_to_cart_button product_type_simple">Add to cart</a>

I tried to change the product_id and everything to be fit to my needs like this,

<a href="/?product_cat=icecream&amp;add-to-cart=<?php echo $id; ?>" rel="nofollow" data-product_id="<?php echo $id; ?>" data-product_sku="" class="button add_to_cart_button product_type_simple">
    <img src="<?php echo get_bloginfo('template_directory'); ?>/images/add_to_cart.png" alt="Add to cart" />
</a>

but it dosen't get saved for some reason (when I get into cart page its empty). I'm trying also to lose the "View Cart" button that gets near when the item is added, if someone can guide me how can I create that button and where to shall I redirect it, it would be perfect (:

thanks !

greW
  • 1,248
  • 3
  • 24
  • 49

4 Answers4

7

It only works in shop page this way. Try this for other pages:

$product = get_product(77);
echo "<a href='" . $product->add_to_cart_url() ."'>add to cart</a>";
Ashish Yadav
  • 1,901
  • 2
  • 17
  • 23
sabarnix
  • 715
  • 4
  • 5
6

Well, you can do it with ajax, you can redirect it to - '?add-to-cart=' and the item will get into the cart. so you will be able to design you'r button however you want ..

Danny
  • 793
  • 1
  • 9
  • 20
2

You can try using the add to cart shortcode.

<?php echo do_shortcode( '[add_to_cart id=' . $id . ']' ) ?>

Assuming you already have $id.

joseconsador
  • 164
  • 1
  • 6
  • 1
    How do you define `$id` to pull the id of the product? – Darren Bachan Feb 09 '17 at 22:14
  • @Darren - You have to enter the ID yourself. WooCommerce has to know which product you intent to show, assuming you're adding this on a custom page and not the product page. – Skovsgaard Aug 20 '18 at 11:54
1

Shortcode already gives you the AJAX functionality.

Try this:

<?php
global $product;
$pid = $product->get_id();
?>
<a href="<?php echo do_shortcode( '[add_to_cart_url id=' . $pid . ']' ) ?>" class="your-classes-here">Add to cart</a>

You'll find more info here: https://docs.woocommerce.com/document/woocommerce-shortcodes/

Hope you'd find this useful.

Pablo
  • 1,875
  • 1
  • 10
  • 11