I want to hide specific products, based on product category for users under the age of 18.
So if the user is not logged in, or if logged in but under the age of 18 years old (date of birth will be set during check out), these products should be hidden on WooCommerce shop and archive pages.
Via code I found online, and trial and error, this is my code attempt:
add_filter( 'woocommerce_product_categories_hide_empty', 'hide_empty_categories' );
function hide_empty_categories( $hide_empty ) {
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$age = (int) $current_user->user_age;
if ( $age < 18 ) {
$hide_empty = true;
}
}
return $hide_empty;
}
Unfortunately without the desired result. Any advice?
To add the birthday field, I use:
function new_add_custom_checkbox_fields() {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping = $chosen_methods[0];
if ($chosen_shipping != 'free_shipping:2'){
add_filter('woocommerce_checkout_fields', function($fields) {
$fields['billing']['billing_date_intervention'] = [
'label' => __('date du jour', 'textdomain'),
'required' => true,
'type' => 'text',
'default' => date("d/m/Y"),
'class' => ['wooccm-required-field'],
'priority' => 125
];
$fields['billing']['billing_date_naissance'] = [
'label' => __('date de naissance', 'textdomain'),
'required' => true,
'type' => 'date',
'class' => ['wooccm-required-field'],
'id' => 'date_of_birth',
'priority' => 70
];
return $fields;
});
}
}
add_action('woocommerce_billing_fields', 'new_add_custom_checkbox_fields');
/**
* Ajout et mise à jour des champs dans la base de donnée
*/
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['billing_date_intervention'] ) ) {
add_post_meta( $order_id, '_billing_date_intervention', sanitize_text_field( $_POST['billing_date_intervention'] ) );
}
if ( ! empty( $_POST['billing_date_naissance'] ) ) {
add_post_meta( $order_id, '_billing_date_naissance', sanitize_text_field( $_POST['billing_date_naissance'] ) );
}
}