We have a WooCommerce store that sells files (MP3/MP4) to registered users and enables the user to play them in the "Downloads" section of their account (we have modified order-downloads.php).
The challenge we are facing is that we would like to enable user to play the MP3 also on the specific product page of the product that they have already purchased (instead of the "Add to cart" button, we would like to show the player if the user is logged in and has previously purchased this product).
I have found various solutions on how to prevent user to buy the same product again, however I don't know how I can combine the code from order-downloads.php and the product template to do this.
So far this is my code attempt, but unfortunately without the desired result. Anyone who can point me in the right direction?
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;
}