| |
| <?php
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| define( 'DOCTORS_ROLE_SLUG', 'wholesale_doctors' );
|
|
|
|
|
|
|
| add_action( 'woocommerce_product_options_general_product_data', function () {
|
| woocommerce_wp_checkbox( [
|
| 'id' => '_restrict_to_doctors',
|
| 'label' => __( 'Restrict purchase to Doctors role only', 'woocommerce' ),
|
| 'description' => __( 'Product is visible to all, but only the Doctors wholesale
|
| role can add it to cart.', 'woocommerce' ),
|
| ] );
|
| } );
|
|
|
| add_action( 'woocommerce_process_product_meta', function ( $post_id ) {
|
| $value = isset( $_POST['_restrict_to_doctors'] ) ? 'yes' : 'no';
|
| update_post_meta( $post_id, '_restrict_to_doctors', $value );
|
| } );
|
|
|
|
|
|
|
| add_filter( 'woocommerce_is_purchasable', function ( $purchasable, $product ) {
|
| if ( 'yes' !== get_post_meta( $product->get_id(), '_restrict_to_doctors', true ) ) {
|
| return $purchasable;
|
| }
|
|
|
| $user = wp_get_current_user();
|
| if ( ! in_array( DOCTORS_ROLE_SLUG, (array) $user->roles, true ) ) {
|
| return false;
|
| }
|
|
|
| return $purchasable;
|
| }, 10, 2 );
|
|
|
|
|
|
|
| add_action( 'woocommerce_single_product_summary', function () {
|
| global $product;
|
| if ( ! $product || 'yes' !== get_post_meta( $product->get_id(),
|
| '_restrict_to_doctors', true ) ) {
|
| return;
|
| }
|
|
|
| $user = wp_get_current_user();
|
| if ( in_array( DOCTORS_ROLE_SLUG, (array) $user->roles, true ) ) {
|
| return;
|
| }
|
|
|
| echo '<p class="woocommerce-info wwp-restricted">' .
|
| esc_html__( 'This product is available for purchase by registered Doctors only.',
|
| 'woocommerce' ) .
|
| '</p>';
|
| }, 25 );
|
|
|
|
|
|
|
| add_filter( 'woocommerce_add_to_cart_validation', function ( $passed, $product_id ) {
|
| if ( 'yes' !== get_post_meta( $product_id, '_restrict_to_doctors', true ) ) {
|
| return $passed;
|
| }
|
|
|
| $user = wp_get_current_user();
|
| if ( ! in_array( DOCTORS_ROLE_SLUG, (array) $user->roles, true ) ) {
|
| wc_add_notice(
|
| __( 'This product is available for purchase by registered Doctors only.',
|
| 'woocommerce' ),
|
| 'error'
|
| );
|
| return false;
|
| }
|
|
|
| return $passed;
|
| }, 10, 2 );
|
|
|
|
|
| add_action( 'wp_head', function () {
|
| if ( ! is_product() ) {
|
| return;
|
| }
|
|
|
| $user = wp_get_current_user();
|
| if ( in_array( DOCTORS_ROLE_SLUG, (array) $user->roles, true ) ) {
|
| return;
|
| }
|
| ?>
|
| <style>
|
| .product:has(.summary .woocommerce-info.wwp-restricted) form.variations_form.cart
|
| .woocommerce-variation-add-to-cart.variations_button {
|
| display: none;
|
| }
|
| </style>
|
| <?php
|
| } );
|
| |
| |
Comments