show download list woocomerce product from order
Mon Dec 11 2023 14:02:36 GMT+0000 (Coordinated Universal Time)
Saved by @amirabbas8643 #php #wordpress
function find_order_with_product_for_user($user_id, $product_id) {
global $wpdb;
// Get the order IDs for the user
$order_ids = $wpdb->get_col("
SELECT DISTINCT order_items.order_id
FROM wp_woocommerce_order_items as order_items
LEFT JOIN wp_woocommerce_order_itemmeta as order_itemmeta ON order_items.order_item_id = order_itemmeta.order_item_id
LEFT JOIN wp_posts as posts ON order_items.order_id = posts.ID
LEFT JOIN wp_postmeta as postmeta ON postmeta.post_id = posts.ID
WHERE posts.post_type = 'shop_order'
AND posts.post_status IN ('wc-processing', 'wc-completed')
AND order_itemmeta.meta_key = '_product_id'
AND order_itemmeta.meta_value = '$product_id'
AND postmeta.meta_key = '_customer_user'
AND postmeta.meta_value = '$user_id'
");
// If orders are found, return the order IDs
if ($order_ids) {
return $order_ids;
}
return false;
}
function course_woocommerce_product_downloads_shortcode($atts) {
// Extract shortcode attributes
$atts = shortcode_atts(
array(
'product_id' => get_the_ID(), // Specify the product ID
),
$atts,
'custom_woocommerce_product_downloads'
);
// Check if the product ID is provided
if (empty($atts['product_id'])) {
return '';
}
// Get the product object
$product = wc_get_product($atts['product_id']);
$order_ids = find_order_with_product_for_user(get_current_user_id(), $atts['product_id']);
// Check if the product is downloadable
if ($product && $product->is_downloadable() && wc_customer_bought_product(get_current_user_id(), get_current_user_id(), get_the_ID())) {
$order = wc_get_order(current($order_ids));
$downloads = $order->get_downloadable_items();
// Check if there are downloads
if ($downloads) {
// Output a list of download files
$output = '<h2>دانلود دوره خریداری شده ' . esc_html($product->get_name()) . '</h2>';
$output .= '<ul>';
foreach ($downloads as $download) {
if($download['product_id'] != $atts['product_id']){
continue;
}
$output .= '<li><a href="' . esc_url($download['download_url']) . '">' . esc_html($download['download_name']) . "</a></li>";
}
$output .= '</ul>';
} else {
$output = '<p>هیچ فایل دانلودی برای این دوره موجود نیست.</p>';
}
} else {
$output = '<p>برای مشاهده فایل ها لطفا ابتدا دوره را خریداری کنید</p>';
}
return $output;
}
add_shortcode('course_woocommerce_product_downloads', 'course_woocommerce_product_downloads_shortcode');



Comments