/*
* Step 1. Add Link (Tab) to My Account menu
*/
add_filter ( 'woocommerce_account_menu_items', 'misha_log_history_link', 40 );
function misha_log_history_link( $menu_links ){
$menu_links = array_slice( $menu_links, 0, 5, true )
+ array( 'log-history' => 'Refund Deposit' )
+ array_slice( $menu_links, 5, NULL, true );
return $menu_links;
}
/*
* Step 2. Register Permalink Endpoint
*/
add_action( 'init', 'misha_add_endpoint' );
function misha_add_endpoint() {
// WP_Rewrite is my Achilles' heel, so please do not ask me for detailed explanation
add_rewrite_endpoint( 'log-history', EP_PAGES );
}
/*
* Step 3. Content for the new page in My Account, woocommerce_account_{ENDPOINT NAME}_endpoint
*/
add_action( 'woocommerce_account_log-history_endpoint', 'misha_my_account_endpoint_content' );
function misha_my_account_endpoint_content() {
global $wpdb;
// this SQL query allows to get all the products purchased by the current user
// in this example we sort products by date but you can reorder them another way
$purchased_products_ids = $wpdb->get_col( $wpdb->prepare(
"
SELECT itemmeta.meta_value
FROM " . $wpdb->prefix . "woocommerce_order_itemmeta itemmeta
INNER JOIN " . $wpdb->prefix . "woocommerce_order_items items
ON itemmeta.order_item_id = items.order_item_id
INNER JOIN $wpdb->posts orders
ON orders.ID = items.order_id
INNER JOIN $wpdb->postmeta ordermeta
ON orders.ID = ordermeta.post_id
WHERE itemmeta.meta_key = '_product_id'
AND ordermeta.meta_key = '_customer_user'
AND ordermeta.meta_value = %s
ORDER BY orders.post_date DESC
",
get_current_user_id()
) );
// some orders may contain the same product, but we do not need it twice
$purchased_products_ids = array_unique( $purchased_products_ids );
// if the customer purchased something
if( !empty( $purchased_products_ids ) ) :
// it is time for a regular WP_Query
$purchased_products = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'post__in' => $purchased_products_ids,
'orderby' => 'post__in'
) );
echo '';
woocommerce_product_loop_start();
while ( $purchased_products->have_posts() ) : $purchased_products->the_post();
the_title();
endwhile;
woocommerce_product_loop_end();
woocommerce_reset_loop();
wp_reset_postdata();
echo '';
else:
echo 'Nothing purchased yet.';
endif;
}
Comments
Post a Comment