How to check selected product in previous customer orders or not

$seletedProduct = 25;
$exist = ‘no’;
if(is_user_logged_in()){      // Check for customer login
$orders = get_posts( array(
‘numberposts’ => -1,
‘meta_key’ => ‘_customer_user’,
‘meta_value’ => get_current_user_id(),
‘post_type’ => ‘shop_order’,
‘post_status’ => array(‘wc-completed’, ‘wc-processing’)
) );
foreach ($orders as $order) {
$WC_Order = new WC_Order($order->ID);
$items = $WC_Order->get_items();
foreach ( $items as $item ) {
if($item[‘product_id’] == $seletedProduct){
$exist = ‘yes’;
}
}
}
}
if($exist == ‘no’){
echo ‘Product not ordered’;
}else{
echo ‘Product already ordered’;
}

Advertisements

Remove shipping method from WooCommerce cart programmatically

add_filter( ‘woocommerce_package_rates’, ‘aviweb_hide_free_shipping_class’, 10, 2 );

function aviweb_hide_free_shipping_class( $rates, $package ) {
echo $in_cart = false;
foreach( WC()->cart->cart_contents as $key => $values ) {
$product_id = $values[‘product_id’];
if ( $product_id == 2 ) {
$in_cart = true;
break;
}
}
if( $in_cart ) {
unset( $rates[‘flat_rate:7’] );
}
return $rates;
}

Add new extra fields for WooCommerce registration with role set

add_action( ‘woocommerce_register_form_start’, ‘aviweb_extra_register_fields’ );
/**
*
* Validate the extra register fields.
*
*/
function aviweb_validate_extra_register_fields( $username, $email, $validation_errors ) {
if ( isset( $_POST[‘user_type’] ) && empty( $_POST[‘user_type’] ) ) {
$validation_errors->add( ‘user_type_error’, __( ‘<strong>Error</strong>: User type is required!.’, ‘woocommerce’ ) );
}
}
add_action( ‘woocommerce_register_post’, ‘aviweb_validate_extra_register_fields’, 10, 3 );
/**
*
* Save the extra register fields.
*
*/
function aviweb_save_extra_register_fields( $customer_id ) {
if ( isset( $_POST[‘user_type’] ) ) {
update_user_meta( $customer_id, ‘user_type’, sanitize_text_field( $_POST[‘user_type’] ) );
$my_user = new WP_User( $customer_id );
if($_POST[‘user_type’] == “subscriber”){
$my_user->set_role( “subscriber” );
}else if($_POST[‘user_type’] == “customer”){
$my_user->set_role( “customer” );
}
}
}
add_action( ‘woocommerce_created_customer’, ‘aviweb_save_extra_register_fields’ );