Skip to content

Instantly share code, notes, and snippets.

@espellcaste
Forked from claudiosanches/functions.php
Last active December 19, 2015 09:09
Show Gist options
  • Save espellcaste/5931010 to your computer and use it in GitHub Desktop.
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.
<?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 &rarr;</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 &rarr;</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