This is code snippet that adds user’s won auctions to cart automatically:
add_action( 'template_redirect', 'afw_add_won_auctions_to_cart', 10 );
function afw_add_won_auctions_to_cart() {
if ( ! is_admin() && is_user_logged_in() ) {
$user_id = get_current_user_id();
$auction_visibility_terms = wc_get_auction_visibility_term_ids();
$product_visibility_in = array( $auction_visibility_terms['sold'] );
$args = array(
'post_type' => 'product',
'posts_per_page' => '-1',
'meta_query' => array(
array(
'key' => '_auction_current_bider',
'value' => $user_id,
),
array(
'key' => '_auction_payed',
'compare' => 'NOT EXISTS',
),
),
'tax_query' => array(
'taxonomy' => 'auction_visibility',
'field' => 'term_taxonomy_id',
'terms' => $product_visibility_in,
'operator' => 'IN',
),
'show_past_auctions' => true,
'auction_arhive' => true,
'fields' => 'ids',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
);
$won_auctions = new WP_Query( $args );
$posts_ids = $won_auctions->posts;
if ( is_array( $posts_ids ) ) {
foreach ( $posts_ids as $posts_id ) {
$found = false;
$product = wc_get_product( $posts_id );
// check if auction ended and has highest bidder
if ( is_object( WC()->cart ) && is_object( $product ) && method_exists( $product, 'get_auction_closed' ) && method_exists( $product, 'get_auction_payed' ) && ! $product->get_auction_payed() && 2 == $product->get_auction_closed() && ( $product->get_stock_quantity() > 0 ) ){
// check if already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $posts_id ) {
$found = true;
}
}
if ( ! $found ) {
WC()->cart->add_to_cart( $posts_id );
}
} else {
WC()->cart->add_to_cart( $posts_id );
}
}
}
}
}
}