Enjoying these plugins? ☕ Buy me a coffee to support ongoing development.

Widget Visibility Manager

Add powerful visibility control rules to all WordPress widgets. Show or hide widgets based on user login status, roles, page types, device types, and date ranges. Create personalized user experiences without code.

Single File v1.0.1 Updated 3 days ago

YT Widget Visibility Manager

Add powerful visibility control rules to all WordPress widgets. Show or hide widgets based on user login status, roles, page types, device types, and date ranges. Create personalized user experiences without code.

Description

The Widget Visibility Manager plugin extends WordPress widgets with advanced visibility rules. Control exactly when and where each widget appears on your site. Perfect for membership sites, e-commerce stores, multi-author blogs, and any site requiring targeted content delivery.

Features

  • Visibility Rules Panel: Collapsible section added to every widget
  • Login Status Control: Show to everyone, logged-in only, or logged-out only
  • User Role Targeting: Display widgets to specific roles (admin, editor, author, etc.)
  • Page Type Filters: Control visibility by front page, blog, posts, pages, archives, search, 404
  • Device Detection: Show/hide widgets on mobile, tablet, or desktop
  • Date Range Scheduling: Display widgets only within specific date ranges
  • Per-Widget Configuration: Each widget has independent visibility settings
  • Global Settings: Enable/disable specific rule types site-wide
  • Status Indicators: Visual badges show active/inactive visibility rules
  • Collapsible Interface: Clean, organized widget forms
  • No Database Tables: Uses WordPress options (lightweight)
  • Translation Ready: Full i18n support
  • Customizer Compatible: Works in WordPress Customizer
  • Block Editor Support: Compatible with widget block editor
  • Secure: Proper capability checks and data sanitization

Installation

  1. Upload yt-widget-visibility-manager.php to /wp-content/plugins/
  2. Upload yt-widget-visibility-manager.css to the same directory
  3. Upload yt-widget-visibility-manager.js to the same directory
  4. Activate the plugin through the 'Plugins' menu
  5. Go to Appearance → Widgets
  6. Configure visibility rules for any widget

Usage

Basic Setup

  1. Go to Appearance → Widgets
  2. Open any widget in a sidebar
  3. Scroll to Visibility Rules section
  4. Click to expand the section
  5. Check Enable visibility rules for this widget
  6. Configure your desired rules
  7. Save the widget

Login Status Rules

Control widget visibility based on authentication:

Everyone

  • Widget shows to all visitors (default)
  • No restrictions applied

Logged-in users only

  • Widget visible only to authenticated users
  • Hidden from guests and visitors

Logged-out users only

  • Widget visible only to non-authenticated visitors
  • Hidden from logged-in users

User Role Rules

Target specific user roles:

  1. Set Login Status to "Logged-in users only" or "Everyone"
  2. Select one or more user roles
  3. Widget shows only to users with selected roles

Available Roles (default WordPress):

  • Administrator
  • Editor
  • Author
  • Contributor
  • Subscriber

Custom Roles:

  • Any custom roles added by plugins also appear
  • Select multiple roles for broader targeting

Leave Empty:

  • Shows to all logged-in users regardless of role

Page Type Rules

Control where widgets appear:

All pages

  • Widget shows everywhere (default)

Front page only

  • Homepage only (static page or blog)

Blog page

  • Main blog posts page

Single posts

  • Individual blog post pages

Pages

  • Static WordPress pages

Archives

  • Category, tag, author, date archives

Search results

  • Search results pages

404 error page

  • Page not found pages

Device Type Rules

Responsive widget display:

All devices

  • Shows on mobile, tablet, desktop (default)

Mobile only

  • Smartphones and small screens
  • Typically < 768px width

Tablet only

  • Tablets and medium screens
  • Typically 768px - 1024px width

Desktop only

  • Laptops and large screens
  • Typically > 1024px width

Date Range Rules

Schedule widget appearance:

  1. Check Enable Date Range
  2. Set Start Date (optional)
  3. Set End Date (optional)
  4. Widget shows only within date range

Examples:

  • Start: 2025-12-01, End: 2025-12-31 (December only)
  • Start: 2025-01-01, End: (empty) (From January onwards)
  • Start: (empty), End: 2025-06-30 (Until end of June)

Settings

Navigate to Settings → Widget Visibility to configure:

Enable Rule Types

Control which rule types are available:

Login Status Rules

  • ✓ Enabled: Show login status dropdown in widgets
  • ✗ Disabled: Hide login status controls

User Role Rules

  • ✓ Enabled: Show user role checkboxes
  • ✗ Disabled: Hide role selection

Page Type Rules

  • ✓ Enabled: Show page type dropdown
  • ✗ Disabled: Hide page type controls

Device Type Rules

  • ✓ Enabled: Show device type dropdown
  • ✗ Disabled: Hide device controls

Date Range Rules

  • ✓ Enabled: Show date range inputs
  • ✗ Disabled: Hide date scheduling

Default Behavior

Hide widgets by default when rules don't match

  • ✓ Checked: Hide widget if rules don't match
  • ✗ Unchecked: Show widget unless explicitly hidden

Use Cases

Membership Site

Show different content to members vs. visitors:

Member-Only Widget:

✓ Enable visibility rules
Login Status: Logged-in users only
User Roles: (leave empty for all members)

Guest Welcome Widget:

✓ Enable visibility rules
Login Status: Logged-out users only
Page Type: Front page only

E-commerce Store

Target different customer segments:

Sale Banner (Limited Time):

✓ Enable visibility rules
Date Range: Enabled
Start Date: 2025-11-25
End Date: 2025-11-30

Mobile App Promotion:

✓ Enable visibility rules
Device Type: Mobile only

Multi-Author Blog

Show widgets based on content type:

Author Bio Widget:

✓ Enable visibility rules
Page Type: Single posts

Category Navigation:

✓ Enable visibility rules
Page Type: Archives

Admin-Only Tools

Hidden utilities for administrators:

Site Stats Widget:

✓ Enable visibility rules
Login Status: Logged-in users only
User Roles: Administrator

Configuration Examples

Welcome Message for New Visitors

Widget: Text Widget
Title: "Welcome!"
Visibility Rules:
  ✓ Enable visibility rules
  Login Status: Logged-out users only
  Page Type: Front page only

Premium Content Teaser

Widget: Custom HTML
Title: "Unlock Premium Features"
Visibility Rules:
  ✓ Enable visibility rules
  Login Status: Logged-in users only
  User Roles: Subscriber

Holiday Promotion

Widget: Image Widget
Title: "Christmas Sale"
Visibility Rules:
  ✓ Enable visibility rules
  Date Range: Enabled
  Start Date: 2025-12-15
  End Date: 2025-12-25

Mobile-Only CTA

Widget: Button Widget
Title: "Download Our App"
Visibility Rules:
  ✓ Enable visibility rules
  Device Type: Mobile only

Blog Sidebar Widget

Widget: Recent Posts
Title: "Latest Articles"
Visibility Rules:
  ✓ Enable visibility rules
  Page Type: Blog

Technical Details

File Structure

yt-widget-visibility-manager.php       # Main plugin file (869 lines)
yt-widget-visibility-manager.css       # Widget form styles (470 lines)
yt-widget-visibility-manager.js        # Dynamic interactions (550 lines)
README-yt-widget-visibility-manager.md # Documentation

Constants Defined

YT_WVM_VERSION   // Plugin version (1.0.0)
YT_WVM_BASENAME  // Plugin basename
YT_WVM_PATH      // Plugin directory path
YT_WVM_URL       // Plugin directory URL

Database Storage

Option Name: yt_wvm_options

Option Structure:

array(
    'enable_login_rules'  => true,
    'enable_role_rules'   => true,
    'enable_page_rules'   => true,
    'enable_device_rules' => true,
    'enable_date_rules'   => true,
    'default_hide'        => false
)

Widget Instance Storage:

$instance['yt_wvm_rules'] = array(
    'visibility_enabled' => true,
    'login_status'       => 'logged_in',
    'user_roles'         => array('administrator', 'editor'),
    'page_type'          => 'all',
    'device_type'        => 'all',
    'date_range'         => array(
        'enabled' => true,
        'start'   => '2025-01-01',
        'end'     => '2025-12-31'
    )
)

WordPress Hooks

Actions

  • plugins_loaded: Load text domain
  • admin_enqueue_scripts: Load CSS/JS on widgets page
  • admin_menu: Add settings page
  • admin_init: Register settings
  • in_widget_form: Render visibility controls

Filters

  • widget_display_callback: Filter widget visibility
  • dynamic_sidebar_params: Add visibility controls to widgets
  • widget_update_callback: Save visibility settings
  • plugin_action_links_{basename}: Add settings link

Conditional Tags Used

  • is_user_logged_in(): Check login status
  • is_front_page(): Front page detection
  • is_home(): Blog page detection
  • is_single(): Single post detection
  • is_page(): Page detection
  • is_archive(): Archive detection
  • is_search(): Search results detection
  • is_404(): 404 page detection
  • wp_is_mobile(): Mobile detection

Device Detection

The plugin uses a custom device detection method:

private function detect_device() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    if (wp_is_mobile()) {
        // Check for tablet patterns
        if (preg_match('/(tablet|ipad|playbook|silk)|(android(?!.*mobile))/i', $user_agent)) {
            return 'tablet';
        }
        return 'mobile';
    }

    return 'desktop';
}

Tablet Detection Patterns:

  • iPad, Android tablets
  • Kindle Fire, Playbook
  • Other tablet-specific patterns

Security Features

  • Capability Checks: manage_options for settings
  • Nonce Verification: All form submissions
  • Input Sanitization: All user input cleaned
    • sanitize_text_field() for text
    • sanitize_key() for role names
  • Output Escaping: All output escaped
    • esc_html() for text
    • esc_attr() for attributes
  • Array Casting: Safe handling of array inputs
  • XSS Prevention: Proper HTML filtering

Performance

Resource Usage

  • Database: 1 option entry + per-widget instance data
  • HTTP Requests: 0 (assets loaded with admin)
  • Memory: < 50 KB
  • Widget Check: Minimal overhead per widget

Load Time Impact

  • Admin Pages: +20-30ms (CSS/JS only on widgets page)
  • Frontend: +5-10ms per widget (conditional checks)
  • Caching: Compatible with all cache plugins

Optimization

  • Conditional Loading: Assets only on widgets/settings pages
  • No Database Tables: Uses lightweight options
  • Early Returns: Skip checks when rules disabled
  • Efficient Checks: Minimal conditional tag calls

Frequently Asked Questions

Which widgets are supported?

All WordPress widgets including:

  • Core widgets (Text, Image, Categories, etc.)
  • Theme widgets
  • Plugin widgets
  • Custom widgets

Do visibility rules work in the Customizer?

Yes, the plugin fully supports the WordPress Customizer.

Are rules compatible with the block editor?

Yes, visibility rules work with widget blocks in WordPress 5.8+.

Can I use multiple rules together?

Yes, all enabled rules must pass for widget to display. Rules use AND logic.

What happens if rules conflict?

Example: Login Status = "Logged-out" + User Roles = "Administrator"

  • Widget will never show (can't be logged-out AND have a role)
  • JavaScript shows a warning in this case

Can I export/import visibility settings?

Not in the current version, but settings are stored in widget instance data and export with widgets.

Does this work with page builders?

It depends on the page builder. If the builder uses WordPress widgets, yes. If it uses custom elements, no.

Can I hide widgets on specific posts/pages?

Not directly. Use Page Type rules to hide on all posts or all pages. For specific pages, consider using categories or custom post types.

Does date range support timezones?

Yes, uses WordPress timezone setting from Settings → General.

What about GDPR compliance?

The plugin doesn't collect or store any personal user data. It only checks current user status and roles.

Troubleshooting

Visibility rules not appearing

Causes:

  • Plugin not activated
  • JavaScript error
  • Theme conflict

Solutions:

  • Verify plugin activation
  • Check browser console for errors
  • Disable other plugins temporarily
  • Try different theme

Widget still showing when it shouldn't

Causes:

  • Visibility rules not enabled for widget
  • Rule type disabled in settings
  • Caching plugin showing cached version

Solutions:

  • Check "Enable visibility rules" is checked
  • Go to Settings → Widget Visibility, verify rule types enabled
  • Clear cache (site cache, browser cache)
  • Test in private/incognito window

Rules not saving

Causes:

  • PHP max_input_vars limit reached
  • JavaScript error preventing save
  • Server timeout

Solutions:

  • Increase max_input_vars in php.ini
  • Check browser console
  • Contact hosting support

Date range not working

Causes:

  • Date range not enabled
  • Timezone mismatch
  • Dates in wrong format

Solutions:

  • Check "Enable Date Range" is checked
  • Verify WordPress timezone in Settings → General
  • Use YYYY-MM-DD format (date picker enforces this)

Device detection not accurate

Causes:

  • User agent spoofing
  • Unconventional device

Solutions:

  • Device detection is based on user agent strings
  • Some edge cases may not be detected correctly
  • Consider using CSS media queries for critical responsive needs

Widgets disappeared after activation

Causes:

  • Global setting "Hide by default" enabled
  • Existing widgets don't have rules enabled

Solutions:

  • Go to Settings → Widget Visibility
  • Uncheck "Hide widgets by default when rules don't match"
  • Re-save settings

Best Practices

Performance

Do:

  • Enable only rule types you need
  • Use simple rules when possible
  • Test with caching enabled

Don't:

  • Enable all rules for every widget
  • Create overly complex rule combinations
  • Forget to clear cache after changes

User Experience

Do:

  • Show appropriate content to each audience
  • Use date ranges for time-sensitive content
  • Test rules from visitor perspective

Don't:

  • Hide critical navigation widgets
  • Create confusing experiences with too many rules
  • Forget to test on actual devices

Maintenance

Do:

  • Document your visibility rules
  • Review rules periodically
  • Remove outdated date ranges

Don't:

  • Set rules and forget them
  • Leave expired promotions visible
  • Overlap conflicting rules

Privacy & Data

What Data is Stored?

  • Widget visibility settings per widget instance
  • Global plugin settings
  • No user-specific data
  • No tracking or analytics

User Detection

The plugin checks:

  • Login status (from WordPress session)
  • User role (from WordPress user object)
  • Page type (from WordPress conditional tags)
  • Device type (from HTTP user agent header)
  • Current date/time (from server time)

GDPR Considerations

  • No personal data collected
  • No cookies set
  • No external API calls
  • No user tracking
  • No analytics or telemetry

Uninstallation

When you delete the plugin:

  1. Widget visibility settings remain in widget instances
  2. Global plugin settings deleted
  3. Widgets revert to default behavior (show everywhere)
  4. No database tables to clean up

Note: To completely remove visibility settings, delete and re-add widgets.

Changelog

1.0.0 (2025-01-XX)

  • Initial release
  • Login status rules (everyone, logged-in, logged-out)
  • User role targeting
  • Page type filters (front, blog, single, page, archive, search, 404)
  • Device detection (mobile, tablet, desktop)
  • Date range scheduling
  • Collapsible interface
  • Status indicators
  • Global settings page
  • WordPress Customizer support
  • Block editor compatibility
  • Translation ready
  • Mobile responsive

Roadmap

Potential future features:

  • Specific page/post selection
  • Custom post type support
  • Taxonomy-based rules
  • IP address targeting
  • Geographic location rules
  • Referrer-based visibility
  • Query string parameter detection
  • Cookie-based rules
  • Time of day scheduling
  • Rule templates
  • Bulk edit visibility
  • Import/export settings
  • Analytics integration
  • Visual rule builder
  • Rule conflicts detection

Developer Notes

Line Count

  • PHP: 869 lines
  • CSS: 470 lines
  • JS: 550 lines
  • Total: 1,889 lines

Extending the Plugin

Add Custom Device Detection

add_filter('yt_wvm_device_type', function($device_type) {
    // Custom device detection logic
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'CustomDevice') !== false) {
        return 'custom';
    }
    return $device_type;
});

Add Custom Visibility Check

add_filter('yt_wvm_check_visibility', function($visible, $rules, $instance) {
    // Custom visibility logic
    if (isset($rules['custom_rule']) && !my_custom_check($rules['custom_rule'])) {
        return false;
    }
    return $visible;
}, 10, 3);

Add Custom Page Type

add_filter('yt_wvm_page_types', function($page_types) {
    $page_types['custom_cpt'] = __('Custom Post Type', 'yt-widget-visibility-manager');
    return $page_types;
});

add_filter('yt_wvm_check_page_type', function($matches, $page_type) {
    if ($page_type === 'custom_cpt') {
        return is_singular('custom_post_type');
    }
    return $matches;
}, 10, 2);

Modify Available Roles

add_filter('yt_wvm_available_roles', function($roles) {
    // Hide certain roles from selection
    unset($roles['subscriber']);
    return $roles;
});

JavaScript API

Access the JavaScript API:

// Get manager instance
var manager = window.WidgetVisibilityManager;

// Initialize widgets manually
manager.initializeWidgets();

// Collect rules from widget
var rules = manager.collectRules($section);

// Validate date range
var isValid = manager.validateDateRange($section);

// Export settings
manager.exportSettings('widget-id');

Contributing

Follow WordPress Coding Standards:

# PHP Code Sniffer
phpcs --standard=WordPress yt-widget-visibility-manager.php

# JavaScript linting
eslint yt-widget-visibility-manager.js

# CSS linting
stylelint yt-widget-visibility-manager.css

Support

For issues, questions, or feature requests:

License

GPL v2 or later

Author

Krasen Slavov


Take control of your widgets with powerful visibility rules!