php 使用 wordpress woocommerce 创建自定义“添加到购物车”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24776080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:28:05  来源:igfitidea点击:

Create custom 'Add to cart' with wordpress woocommerce

phpwordpresswoocommerce

提问by greW

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,

我在 woocommerce 模板之外的页面中获取特定产品,我需要添加“添加到购物车”按钮。我查看了代码,我看到 woocommerce 是这样做的,

<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,

我试图改变 product_id 和一切以适应我这样的需求,

<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 !

谢谢 !

采纳答案by Danny

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 ..

好吧,你可以用 ajax 来做,你可以将它重定向到 - '?add-to-cart=' 并且项目将进入购物车。所以你可以设计你想要的按钮..

回答by sabarnix

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>";

回答by joseconsador

You can try using the add to cart shortcode.

您可以尝试使用添加到购物车的短代码。

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

Assuming you already have $id.

假设你已经有了 $id。

回答by Pablo

Shortcode already gives you the AJAX functionality.

简码已经为您提供了 AJAX 功能。

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/

您可以在此处找到更多信息:https: //docs.woocommerce.com/document/woocommerce-shortcodes/

Hope you'd find this useful.

希望你会发现这很有用。