我们的eCommerce是在WordPress/WooCommerce中构建的。网站的其余部分都是用Laravel构建的。例如,当用户在domain.com/shop上将产品添加到购物车中,然后从domain.com/shop导航到domain.com/laravel-page时,我们希望在他们添加的任何产品的标题中保留购物车图标。从header小部件中删除产品并不那么重要,只需使用continue to cart/checkout按钮查看它们即可。对实现这一点有什么想法吗?我知道WooCommerce做了一系列的曲奇。这是我们可以利用的东西吗?谢谢!
发布于 2018-12-08 21:53:02
假设您的WordPress和Laravel在同一个域中,您可以对WordPress后端进行ajax调用以获取购物车数据。
进行ajax调用的jQuery
(function ($) {
$( document ).ready(function() {
$.ajax ({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
dataType: 'JSON',
success: function (resp) {
if (resp.success) {
// build your cart details
}
else {
// handle the error
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert ('Request failed: ' + thrownError.message) ;
},
}) ;
}) ;
})(jQuery) ;
在主题functions.php
文件中注册ajax调用
<?php
// if the ajax call will be made from JS executed when user is logged into WP
add_action ('wp_ajax_call_your_function', 'get_woocommerce_cart_data') ;
// if the ajax call will be made from JS executed when no user is logged into WP
add_action ('wp_ajax_nopriv_call_your_function', 'get_woocommerce_cart_data') ;
function get_woocommerce_cart_data () {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
// build the output array
$out = array();
foreach($items as $item => $values) {
// get product details
$getProductDetail = wc_get_product( $values['product_id'] );
$out[$item]['img'] = $getProductDetail->get_image();
$out[$item]['title'] = $getProductDetail->get_title();
$out[$item]['quantity'] = $values['quantity'];
$out[$item]['price'] = get_post_meta($values['product_id'] , '_price', true);
}
// retun the json
wp_send_json_success($out);
}
https://stackoverflow.com/questions/53685518
复制