Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Tag: Roles

WooCommerce: Set role‑based pricing (simple example)

Posted on August 19, 2025 By Admin No Comments on WooCommerce: Set role‑based pricing (simple example)

WooCommerce: Set Role-Based Pricing (Simple Example)

If you want to offer different product prices to customers based on their user roles in WooCommerce, this guide will help you implement role-based pricing quickly and effectively. By default, WooCommerce does not support pricing variations by user role, but with a small code snippet, you can customize prices for roles like wholesale customers, subscribers, or any custom role.

Quick Fix: How to Set Role-Based Pricing in WooCommerce

  1. Identify the user roles you want to target.
  2. Add a code snippet to your theme’s functions.php or a custom plugin.
  3. Customize the price adjustments in the snippet according to your roles.
  4. Test by logging in as users with different roles to verify prices change accordingly.

Why This Happens

WooCommerce uses a single price field per product by default, which applies universally to all customers. It does not differentiate pricing based on user roles or customer groups out of the box. To offer role-based pricing, you need to programmatically adjust the displayed price depending on the logged-in user’s role. This is commonly needed for wholesale stores, membership discounts, or tiered pricing strategies.

Requirements

  • WooCommerce installed and activated on your WordPress site.
  • Basic knowledge of editing theme files or creating a simple plugin.
  • Access to your site’s file system or WordPress admin editor.
  • Understanding of user roles in WordPress/WooCommerce.

Step-by-Step: Implement Role-Based Pricing in WooCommerce

  1. Backup your site: Always back up your site before editing code.
  2. Access your theme’s functions.php file: Use FTP, cPanel File Manager, or WordPress Appearance > Theme Editor.
  3. Copy and paste the following code snippet at the end of functions.php:
/**
 * Adjust WooCommerce product price based on user role.
 */
add_filter( 'woocommerce_product_get_price', 'custom_role_based_price', 10, 2 );
add_filter( 'woocommerce_product_get_regular_price', 'custom_role_based_price', 10, 2 );
add_filter( 'woocommerce_product_get_sale_price', 'custom_role_based_price', 10, 2 );

function custom_role_based_price( $price, $product ) {
    if ( is_admin() ) {
        return $price; // Do not change price in admin area
    }

    if ( ! is_user_logged_in() ) {
        return $price; // Only modify price for logged-in users
    }

    $user = wp_get_current_user();
    $roles = (array) $user-roles;

    // Example role-based pricing adjustments
    if ( in_array( 'wholesale_customer', $roles ) ) {
        // 20% discount for wholesale customers
        $price = $price * 0.8;
    } elseif ( in_array( 'subscriber', $roles ) ) {
        // 10% discount for subscribers
        $price = $price * 0.9;
    }

    return $price;
}
  1. Save the file.
  2. Test your changes: Log in as a user with the wholesale_customer role and check product prices. Then test with a subscriber and a non-logged-in user to confirm pricing differences.

Common Pitfalls

  • Editing the wrong file: Always use a child theme or a custom plugin to avoid losing changes during theme updates.
  • Role names mismatch: Ensure the role slugs you use in the code exactly match the roles assigned to users.
  • Price caching: Some caching plugins or server-side caches may serve cached prices. Clear caches after applying changes.
  • Admin area price changes: The snippet avoids changing prices in the admin to prevent confusion during product editing.
  • Not handling variable products: This example works for simple products. Variable products require additional handling.

Works On

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed
Hosting Panels cPanel, Plesk, DirectAdmin
WordPress Versions 5.0 and above
WooCommerce Versions 3.0 and above

FAQ

Q: Can I add more roles or different discounts?
A: Yes. Simply add more elseif blocks inside the function checking for other roles and set your desired price adjustments.
Q: How do I create a custom user role like wholesale_customer?
A: Use a role management plugin like “User Role Editor” or add code to register a new role with add_role() in WordPress.
Q: Does this work with variable products?
A: This snippet targets simple products. Variable products require hooking into variation prices separately, which involves more complex code.
Q: Will this affect the price stored in the database?
No. This code only changes the price displayed on the front end dynamically. The original product price in the database remains unchanged.
Q: How can I prevent caching issues with role-based pricing?
Exclude pages with dynamic pricing from caching or use cache plugins that support dynamic content based on user roles.
…
WooCommerce How‑tos

Add a custom user role with specific capabilities

Posted on August 19, 2025 By Admin No Comments on Add a custom user role with specific capabilities

Add a Custom User Role with Specific Capabilities in WordPress

When managing a WordPress site, you might need to create a custom user role tailored to your specific needs. This allows you to control exactly what users assigned to this role can and cannot do. The quick fix is to add a custom user role programmatically using WordPress functions, specifying the capabilities you want to grant.

Quick Fix: Add a Custom User Role in WordPress

  1. Open your theme’s functions.php file or create a custom plugin.
  2. Use the add_role() function to define the new role and its capabilities.
  3. Save the changes and assign the new role to users via the WordPress admin panel.

Why This Happens

WordPress comes with predefined user roles like Administrator, Editor, Author, Contributor, and Subscriber. However, these roles might not fit every use case. For example, you may want a role that can moderate comments but cannot publish posts, or a role that can manage WooCommerce orders but not access other admin areas. Adding a custom user role with specific capabilities lets you tailor user permissions precisely, improving security and workflow.

Requirements

  • Access to your WordPress site’s files (via FTP, cPanel, or hosting file manager).
  • Basic knowledge of PHP and WordPress theme/plugin editing.
  • Administrator access to the WordPress admin dashboard.

Step-by-Step: How to Add a Custom User Role with Specific Capabilities

  1. Backup your site — Always back up your site files and database before making code changes.
  2. Choose where to add the code — You can add the code to your theme’s functions.php file or create a simple custom plugin.
  3. Write the code to add the role — Use the add_role() function to create the new role and assign capabilities.
  4. Save and upload the file — If editing locally, upload the modified file to your server.
  5. Assign the new role to users — Go to WordPress admin Users Edit user Role dropdown to assign the custom role.

Code Snippet: Adding a Custom User Role

<?php
function add_custom_user_role() {
    add_role(
        'custom_moderator', // Role slug
        'Custom Moderator', // Display name
        array(
            'read' =true, // Can read content
            'edit_posts' =false, // Cannot edit posts
            'delete_posts' =false, // Cannot delete posts
            'moderate_comments' =true, // Can moderate comments
            'upload_files' =true, // Can upload files
            'manage_categories' =false, // Cannot manage categories
        )
    );
}
add_action('init', 'add_custom_user_role');
?>

This example creates a role called “Custom Moderator” that can read content, moderate comments, and upload files but cannot edit or delete posts.

Removing a Custom Role

If you want to remove the custom role later, use the remove_role() function:

<?php
function remove_custom_user_role() {
    remove_role('custom_moderator');
}
add_action('init', 'remove_custom_user_role');
?>

Note: Removing a role does not delete users assigned to it. You should reassign those users to another role before removing.

Common Pitfalls When Adding Custom User Roles

  • Adding roles on every page load: Calling add_role() on every page load can cause issues. It’s best to run it once or check if the role exists before adding.
  • Incorrect capability names: Using invalid or misspelled capabilities will result in unexpected behavior. Refer to the WordPress Roles and Capabilities documentation for valid capability names.
  • Not assigning the role to users: After adding a role, you must assign it to users manually or programmatically.
  • Forgetting to remove roles on plugin deactivation: If you add roles via a plugin, consider cleaning up by removing roles on plugin deactivation.
  • Role conflicts: Avoid using role slugs that conflict with existing roles or plugins.

Works on

  • Web servers: Apache, Nginx, LiteSpeed
  • Hosting panels: cPanel, Plesk, DirectAdmin
  • WordPress versions: 4.0 and above (recommended to use latest stable version)
  • Compatible with both single and multisite WordPress installations

FAQ

Q1: Can I add multiple custom roles at once?
A: Yes, you can call add_role() multiple times with different slugs and capabilities within the same function or hook.
Q2: How do I check if a role already exists before adding it?
A: Use get_role('role_slug'). It returns null if the role does not exist. Example:
if (null === get_role('custom_moderator')) {
    add_role(...);
}
Q3: Can I modify capabilities of an existing role?
A: Yes, use get_role('role_slug') to get the role object, then add or remove capabilities with add_cap() and remove_cap().
Q4: Will custom roles be removed if I switch themes?
A: If you add roles in your theme’s functions.php, switching themes will remove those roles. To keep roles persistent, use a custom plugin.
Q5: How do I assign a custom role to a user programmatically?
A: Use the wp_update_user() function. Example:
wp_update_user(array(
    'ID' =$user_id,
    'role' ='custom_moderator'
));
…
Admin & Blocks

Fix “Sorry, you are not allowed to access this page”

Posted on August 19, 2025 By Admin No Comments on Fix “Sorry, you are not allowed to access this page”

Fix “Sorry, you are not allowed to access this page” in WordPress

If you see the message “Sorry, you are not allowed to access this page” when trying to access your WordPress admin dashboard or certain pages, it usually means your user permissions or site configuration are misconfigured. This error can block you from managing your site, but the fix is often straightforward.

Quick fix: Reset your user roles and capabilities or fix your site’s .htaccess or Nginx config to restore proper access.

Quick Fix

  1. Access your WordPress database via phpMyAdmin or a database client.
  2. Run this SQL query to reset your admin user capabilities (replace 1 with your user ID if different):
DELETE FROM wp_usermeta WHERE user_id = 1 AND meta_key = 'wp_capabilities';
INSERT INTO wp_usermeta (user_id, meta_key, meta_value) VALUES (1, 'wp_capabilities', 'a:1:{s:13:"administrator";b:1;}');
  1. Check your .htaccess (Apache) or Nginx config for incorrect rules blocking access.
  2. Clear your browser cache and cookies, then log in again.

Why This Happens

  • Corrupted user roles or capabilities: Plugins or manual changes can accidentally remove or alter administrator capabilities, causing WordPress to block access.
  • Incorrect file permissions or ownership: Server permissions that restrict access to key WordPress files can trigger this error.
  • Misconfigured .htaccess or Nginx rules: Security rules or redirects may unintentionally block admin pages.
  • Plugin or theme conflicts: Faulty or incompatible plugins/themes can interfere with user permissions.
  • Database issues: Corrupted or missing database entries related to user roles.

Step-by-step Fix

1. Reset Administrator Capabilities via Database

Use phpMyAdmin or your preferred database tool to run these commands. Replace wp_ with your database prefix if different, and 1 with your admin user ID if needed.

DELETE FROM wp_usermeta WHERE user_id = 1 AND meta_key = 'wp_capabilities';

INSERT INTO wp_usermeta (user_id, meta_key, meta_value) VALUES (1, 'wp_capabilities', 'a:1:{s:13:"administrator";b:1;}');

This removes any corrupted capabilities and restores administrator rights.

2. Check and Fix File Permissions

Connect to your server via SSH or FTP and run these commands to set correct permissions:

find /path/to/wordpress/ -type d -exec chmod 755 {} ;
find /path/to/wordpress/ -type f -exec chmod 644 {} ;

Replace /path/to/wordpress/ with your actual WordPress root directory.

3. Verify .htaccess (Apache) or Nginx Configuration

For Apache: Check your .htaccess file in the WordPress root. It should contain the standard WordPress rules:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

If you have custom rules blocking access, comment them out or remove them temporarily.

For Nginx: Check your site configuration file, usually located in /etc/nginx/sites-available/. Ensure your location blocks allow access to /wp-admin and /wp-login.php. A minimal working example:

location /wp-admin/ {
    try_files $uri $uri/ /index.php?$args;
}

location = /wp-login.php {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # adjust PHP version/socket
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Reload Nginx after changes:

sudo nginx -t
sudo systemctl reload nginx

4. Disable All Plugins Temporarily

If the problem persists, disable plugins by renaming the plugins folder via FTP or SSH:

mv /path/to/wordpress/wp-content/plugins /path/to/wordpress/wp-content/plugins-disabled

Try accessing the admin again. If successful, rename the folder back and reactivate plugins one by one to find the culprit.

5. Switch to Default Theme

Rename your active theme folder to force WordPress to use a default theme like Twenty Twenty-One:

mv /path/to/wordpress/wp-content/themes/your-active-theme /path/to/wordpress/wp-content/themes/your-active-theme-disabled

Check if access is restored.

Works on

Environment Notes
Apache Fixes .htaccess and permissions issues
Nginx Fixes server config for admin access
cPanel Access phpMyAdmin, file manager, and terminal for fixes
Plesk Use database manager and file manager for troubleshooting
LiteSpeed Similar to Apache, check .htaccess and permissions

FAQ

Q1: I can’t access phpMyAdmin. How else can I reset user capabilities?

If you have SSH access, you can use WP-CLI commands:

wp user set-role 1 administrator

This sets user ID 1 to administrator.

Q2: Could a plugin cause this error?

Yes. Plugins that modify user roles or security plugins can cause permission issues. Disable plugins temporarily to test.

Q3: What if I still can’t access wp-admin

…
Fixes & Errors

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme

    Also by the maker of MySurveyReviews.com