如果购买了产品,请删除WooCommerce单产品页面上的添加到购物车按钮,然后显示MP3播放器
我们有一个WooCommerce商店,该商店出售文件(MP3/MP4)以注册用户,并使用户可以在其帐户的“下载”部分中播放它们(我们已经修改了 order-downloads.php )。
我们面临的挑战是,我们希望使用户还可以在他们已经购买的产品的特定产品页面上播放mp3(而不是“添加到购物车”按钮,我们想向播放器展示用户已登录并以前购买了此产品)。
我找到了有关如何防止用户再次购买同一产品的各种解决方案,但是我不知道如何将代码从order-downloads.php和产品模板组合起来。
到目前为止,这是我的代码尝试,但不幸的是没有预期的结果。谁能将我指向正确的方向?
add_filter( 'woocommerce_loop_add_to_cart_link', 'customizing_add_to_cart_button', 10, 2 );
function customizing_add_to_cart_button( $link, $product ){
$bought = false;
if( is_user_logged_in() ){
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-completed' // Only orders with status "completed"
) );
// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {
$order = wc_get_order( $customer_order->ID );
// Going through each current customer order items
foreach($order->get_items() as $item_id => $item_values){
if($item_values['product_id'] == $product->id){
$bought = true;
break;
}
}
}
}
if($bought){
global $product;
$downloads = array();
$user_id = get_current_user_id();
$downloads = wc_get_customer_available_downloads($user_id);
if (!empty($downloads)) {
foreach ($downloads as $download) {
if ($download['product_id'] === $product->get_id()) {
$thelink = $download['download_url'];
}
}
}
/* $add_to_cart_url = site_url($thelink); */
$button_text = __('[audio src='.$thelink.']', 'woocommerce');
} else {
$add_to_cart_url = $product->add_to_cart_url();
$button_text = $product->add_to_cart_text();
}
$link = sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button product_type_%s">%s</a>',
esc_url( $add_to_cart_url ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->product_type ),
esc_html( $button_text )
);
return $link;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有多种方法可以隐藏/替换WooCommerce中的添加到购物车按钮。这是弄清楚哪种挂钩最适合您的问题的问题。
由于您不仅想隐藏“添加到购物车”按钮,而且还想根据一些条件执行此操作,我们将首先应用一个执行多个检查的自定义功能:
已经
如果 和所需的显示。
对于单个产品页面:
用于商店和档案页面:
There are multiple ways to hide/replace an add to cart button in WooCommerce. It's a matter of figuring out which hooks are most suitable for your question.
Since you don't just want to hide the add to cart button, but want to do this based on a few conditions, we will first apply a custom function that performs several checks:
If all those conditions are met, we return the file url, if NOT, we return an empty string:
Then it is just a matter of calling the function, from the desired page and the desired display.
For the single product page:
For shop and archives pages: