-
-
Save espellcaste/5931010 to your computer and use it in GitHub Desktop.
WooCommerce - Não permitir usuário comprar o mesmo produto mais de uma vez.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function cs_woocommere_buy_once() { | |
global $woocommerce; | |
if ( is_checkout() ) { | |
if ( ! is_user_logged_in() ) { | |
$woocommerce->add_error( | |
sprintf( | |
__( 'Desculpe, mas você deve estar logado para finalizar esta compra. <a href="%s">Fazer login →</a>', 'woocommerce'), | |
get_permalink( woocommerce_get_page_id( 'myaccount' ) ) | |
) | |
); | |
wp_redirect( get_permalink( woocommerce_get_page_id( 'cart' ) ) ); | |
exit; | |
} | |
$product_id = '1279'; // Alterar o id do produto aqui! | |
$bought = false; | |
$customer_orders = get_posts( array( | |
'numberposts' => -1, | |
'meta_key' => '_customer_user', | |
'meta_value' => get_current_user_id(), | |
'post_type' => 'shop_order', | |
'post_status' => 'publish' | |
) ); | |
foreach ( $customer_orders as $order_data ) { | |
$order = new WC_Order( $order_data->ID ); | |
foreach ( $order->get_items() as $item ) { | |
if ( $product_id == $item['product_id'] ) { | |
$bought = true; | |
break; | |
} | |
} | |
} | |
if ( $bought ) { | |
$woocommerce->add_error( | |
sprintf( | |
__( 'Desculpe, mas você não pode comprar %s de novo! <a href="%s">Retornar para loja →</a>', 'woocommerce'), | |
'<strong>' . get_the_title( $product_id ) . '</strong>', | |
get_permalink( woocommerce_get_page_id( 'shop' ) ) | |
) | |
); | |
wp_redirect( get_permalink( woocommerce_get_page_id( 'cart' ) ) ); | |
exit; | |
} | |
} | |
} | |
add_action( 'the_post', 'cs_woocommere_buy_once', 10 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment