WooCommerce:ユーザーの役割に応じて特定の商品の購入を制限する

Last Updated:2023年07月17日| | コメントを残す

WordPress WooCommerce ショッピングモールでは、特定の商品は特定のユーザーロールのユーザーのみを購入でき、一般の顧客やゲストは購入できないように制限したい場合があります。

この場合、 WooCommerce メンバーシップのプラグインを使用することができます。 WooCommerce メンバーシッププラグインを使用すると、プランを作成します(たとえば、ブロンズプラン、シルバープラン、ゴールドプランなど)、ユーザーの評価に基づいて制限できます。

洗練された会員制サイトを運営する必要がなく、プラグインを使用せずに特定のユーザーの役割に応じて特定の商品の購入を制限したい場合は、下記のコードを応用してください。

WooCommerce:ユーザーの役割に応じて特定の商品の購入を制限する

特定の商品は、特定のユーザーロールのメンバーのみが購入できるように制限したい場合は、以下のコードを使用できます。 以下のコードは Limit product to specific user role ドキュメントに提示されたコードを応用したものです。

通知パネルで制限する商品のIDを入力する機能を追加しました。

// How to Restrict WooCommerce Products By User Roles
// Add settings page under the WooCommerce menu

<?php

function theme_enqueue_styles() {
    wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', [] );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', 20 );

function avada_lang_setup() {
	$lang = get_stylesheet_directory() . '/languages';
	load_child_theme_textdomain( 'Avada', $lang );
}
add_action( 'after_setup_theme', 'avada_lang_setup' );

/**
 * @snippet       Simplify Checkout if Only Virtual Products
 * @how-to        Get CustomizeWoo.com FREE
 * @sourcecode    https://businessbloomer.com/?p=78351
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.4
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
// Add settings page under the WooCommerce menu
function yourprefix_wpf_add_settings_page() {
    add_submenu_page(
        'woocommerce',
        'Restricted Products',
        'Restricted Products',
        'manage_options',
        'restricted-products',
        'yourprefix_wpf_settings_page_callback'
    );
}
add_action('admin_menu', 'yourprefix_wpf_add_settings_page');

// Render the settings page
function yourprefix_wpf_settings_page_callback() {
    // Check if the current user has the 'manage_options' capability
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.', 'textdomain'));
    }

    ?>
    <div class="wrap">
        <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
        <form action="options.php" method="post">
            <?php
            settings_fields('wpf_settings');
            do_settings_sections('wpf_settings');
            submit_button('Save Changes');
            ?>
        </form>
    </div>
    <?php
}

// Register settings, sections, and fields
function yourprefix_wpf_register_settings() {
    register_setting('wpf_settings', 'wpf_restricted_products', array(
        'type' => 'string',
        'sanitize_callback' => 'yourprefix_wpf_sanitize_restricted_products'
    ));

    add_settings_section('wpf_main_section', 'Main Settings', null, 'wpf_settings');

    add_settings_field('wpf_restricted_products', 'Restricted Product IDs', 'yourprefix_wpf_restricted_products_callback', 'wpf_settings', 'wpf_main_section');
}
add_action('admin_init', 'yourprefix_wpf_register_settings');

// Render the input field for restricted products
function yourprefix_wpf_restricted_products_callback() {
    $restricted_products = get_option('wpf_restricted_products', '');
    echo '<input name="wpf_restricted_products" id="wpf_restricted_products" type="text" value="' . esc_attr($restricted_products) . '" class="regular-text" placeholder="123,567" />';
    echo '<p class="description">Enter the restricted product IDs separated by commas.</p>';
}

// Sanitize the input value for restricted products
function yourprefix_wpf_sanitize_restricted_products($input) {
    $input = preg_replace('/[^0-9,]/', '', $input);
    return $input;
}

// restrict products

if (!function_exists('yourprefix_wpf_is_current_user_role')) {
    function yourprefix_wpf_is_current_user_role($roles_to_check) {
        $current_user       = wp_get_current_user();
        $current_user_roles = (empty($current_user->roles) ? array('') : $current_user->roles);
        $roles_intersect    = array_intersect($current_user_roles, $roles_to_check);
        return (!empty($roles_intersect));
    }
}

if (!function_exists('yourprefix_wpf_do_hide_product')) {
    function yourprefix_wpf_do_hide_product($product_id_to_check) {
        $restricted_products_option = get_option('wpf_restricted_products', '');
        $products_to_hide = array_map('intval', array_filter(explode(',', $restricted_products_option)));

        $roles_to_hide_for = array('customer');
        $allowed_roles     = array('practitioner');

        return (
            in_array($product_id_to_check, $products_to_hide) &&
            (!is_user_logged_in() || yourprefix_wpf_is_current_user_role($roles_to_hide_for)) &&
            !yourprefix_wpf_is_current_user_role($allowed_roles)
        );
    }
}

add_filter('woocommerce_is_purchasable', 'yourprefix_wpf_product_purchasable_by_user_role', 10, 2);
if (!function_exists('yourprefix_wpf_product_purchasable_by_user_role')) {
    function yourprefix_wpf_product_purchasable_by_user_role($purchasable, $product) {
        return (yourprefix_wpf_do_hide_product($product->get_id()) ? false : $purchasable);
    }
}

// Display a custom message on the shop page for restricted products
function yourprefix_wpf_display_shop_message() {
    global $product;

    if (yourprefix_wpf_do_hide_product($product->get_id())) {
        echo '<p class="not-purchasable-message">This product is not purchasable.</p>';
        remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
    }
}
add_action('woocommerce_after_shop_loop_item', 'yourprefix_wpf_display_shop_message', 9);

// Display a custom message on the single product page for restricted products
function yourprefix_wpf_display_single_product_message() {
    global $product;

    if (yourprefix_wpf_do_hide_product($product->get_id())) {
        echo '<p class="not-purchasable-message">This product is not purchasable.</p>';
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
    }
}
add_action('woocommerce_single_product_summary', 'yourprefix_wpf_display_single_product_message', 29);

上記のコードをテーマ(チャイルドテーマ)の関数ファイルに追加します。 上記のコードを使用すると、 WordPress 管理ページ » WooCommerce (WooCommerce) » Restricted Products メニュー項目が作成されます。

WooCommerce:ユーザーの役割に応じて特定の商品の購入を制限する

Restricted Products IDsに販売を制限する商品IDをコンマで購入して入力するようにします。

その後、 施術者 ユーザーの役割だけがその商品を購入できます。

WooCommerce:ユーザーの役割に応じて特定の商品の購入を制限する

一般のお客様やゲスト(お客様)が該当商品に近づくと、上の図のように 「This product is not purchasable」が表示されます。 このフレーズはコードで変更できます。

このフレーズの色などのスタイルは CSSで制御できます。

.not-purchasable-message {
    color: #a00;
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 10px;
}

上記のコードを Flatsomeテーマでテストしたのでうまくいきました。 Avadaでテストしてみると、カートのボタンは消えますが、「This product is not purchasable.」 テキストは表示されません。 WooCommerce フックをチェックして別のフックで試すことができます。

オプション商品では、上記のコードの動作をテストしていません。 オプション商品で動作しない場合は、オプション商品を含めるようにコードを修正してご使用ください。

参照


コメントを残す

コメント

割引ニュース
DiviレイアウトAI発売記念割引!
AIで画像、テキスト、コーディング、フルページレイアウトを生成可能
ベストセラー WordPress テーマDivi
0
仕事
0
시간
0
0
期間限定
You This Coupon Code in Checkout
Click the code to Copy