Dynamically assign random background colors or images on each page load. Configure custom colors/images globally or per category/tag. Perfect for creative sites, portfolios, and dynamic visual experiences.
The Random Background Generator plugin injects random backgrounds into your WordPress site. Choose from solid colors, images, or a mix of both. Set backgrounds to change on every page load, daily, or per session. Assign specific backgrounds to categories and tags for targeted visual themes.
- Random Backgrounds: Colors or images selected randomly
- Background Types: Solid colors, images, or mixed mode
- Change Frequency: Every page load, daily, or per session
- Category-Specific: Assign backgrounds to categories
- Tag-Specific: Assign backgrounds to tags (optional)
- Post Type Support: Different backgrounds per post type
- Color Management: Add unlimited colors with color picker
- Image Management: Upload and manage background images
- Image Settings: Size, position, repeat, attachment control
- Smooth Transitions: Optional CSS transitions
- Target Element: Apply to any CSS selector (body, containers, etc.)
- Live Preview: Generate random previews in admin
- Session Persistence: Keep same background during user session
- Daily Backgrounds: One background per day
- Fallback Color: Backup color when no backgrounds configured
- Inline CSS Injection: Lightweight, no external files
- Custom CSS: Add your own styling rules
- Translation Ready: Full i18n support
- No Database Tables: Uses WordPress options
- Upload
yt-random-background-generator.phpto/wp-content/plugins/ - Upload
yt-random-background-generator.cssto the same directory - Upload
yt-random-background-generator.jsto the same directory - Activate the plugin through the 'Plugins' menu
- Go to Settings → Random Backgrounds
- Configure your colors or images
- Save settings
- Go to Settings → Random Backgrounds
- Check Enable Random Backgrounds
- Select Background Type (Color, Image, or Mixed)
- Add colors or images
- Save settings
- Click Add Color button
- Click the color box to open color picker
- Select your desired color
- Repeat to add more colors
- Click Remove to delete unwanted colors
- Click Add Image button
- Select image from Media Library (or upload new)
- Click Use This Image
- Image appears in the list
- Click Remove to delete unwanted images
Every page load
- New random background on each page refresh
- Most dynamic option
- Different for every visitor
Once per day
- Same background for all visitors on a given day
- Changes at midnight (server timezone)
- Consistent daily theme
Once per session
- Same background for duration of user session
- Changes when user closes browser
- Consistent per-visitor experience
- Enable Category Backgrounds
- Scroll to Category Backgrounds table
- For each category:
- Select Type (Color or Image)
- Enter color hex code or image URL
- Save settings
When viewing posts in that category, the specific background appears instead of random selection.
Background Size
- Cover: Image covers entire area (recommended)
- Contain: Image fits within area, may show gaps
- Auto: Original image size
Background Position
- Center, Top Left, Top Center, Top Right, Bottom Center
Background Repeat
- No Repeat (recommended for photos)
- Repeat (for patterns)
- Repeat X/Y (horizontal/vertical tiling)
Background Attachment
- Fixed: Parallax effect (image stays fixed while scrolling)
- Scroll: Image scrolls with page
Target Element
- CSS selector for background application
- Default:
body - Examples:
.site-content,#main,.hero-section
Transitions
- Enable smooth background transitions
- Set duration (e.g., 0.5s, 1s, 2s)
Fallback Color
- Backup color when no backgrounds configured
- Default: white (#ffffff)
Custom CSS
- Add additional CSS rules
- Applied alongside generated background CSS
Background Type: Solid Colors
Colors: #e74c3c, #3498db, #2ecc71, #f39c12, #9b59b6, #1abc9c
Change Frequency: Every page load
Transition: Enabled (0.5s)
Background Type: Background Images
Images: [5-10 high-res photos]
Image Size: Cover
Image Attachment: Fixed (Parallax)
Change Frequency: Once per day
Background Type: Mixed
Colors: #34495e, #2c3e50, #7f8c8d
Images: [3-4 abstract patterns]
Change Frequency: Every page load
Transition: Enabled (1s)
Background Type: Solid Colors
Enable Categories: Yes
Category Backgrounds:
- Technology: #3498db (blue)
- Design: #e74c3c (red)
- Lifestyle: #2ecc71 (green)
Change Frequency: Session
Background Type: Background Images
Images: [7 images - one per day of week]
Change Frequency: Once per day
Image Size: Cover
Target Element: .site-content
Display different vibrant backgrounds on each project page visit:
Type: Mixed
Colors: 5 brand colors
Images: 3 texture patterns
Frequency: Every page load
Showcase different photos as full-page backgrounds:
Type: Images
Images: 20 portfolio photos
Size: Cover
Attachment: Fixed
Frequency: Daily
Different color schemes for different blog topics:
Type: Colors
Enable Categories: Yes
Tech posts: Blue background
Food posts: Warm orange
Travel posts: Green tones
Change background daily leading up to event:
Type: Images (countdown themed)
Frequency: Daily
Transition: Enabled
Random inspiring backgrounds for visitors:
Type: Mixed
Colors: 3 gradient-friendly colors
Images: 5 motivational scenes
Frequency: Session
yt-random-background-generator.php # Main plugin file (1,024 lines)
yt-random-background-generator.css # Admin/frontend styles (584 lines)
yt-random-background-generator.js # Admin interactions (456 lines)
README-yt-random-background-generator.md # Documentation
YT_RBG_VERSION // Plugin version (1.0.0)
YT_RBG_BASENAME // Plugin basename
YT_RBG_PATH // Plugin directory path
YT_RBG_URL // Plugin directory URLOption Name: yt_rbg_options
Option Structure:
array(
'enabled' => true,
'background_type' => 'color', // 'color', 'image', 'mixed'
'colors' => array('#3498db', '#e74c3c', '#2ecc71'),
'images' => array('https://example.com/img1.jpg'),
'image_size' => 'cover',
'image_position' => 'center center',
'image_repeat' => 'no-repeat',
'image_attachment' => 'fixed',
'change_frequency' => 'every_load', // 'every_load', 'daily', 'session'
'persist_session' => false,
'target_element' => 'body',
'custom_css' => '',
'enable_categories' => false,
'category_backgrounds' => array(
123 => array('type' => 'color', 'value' => '#3498db')
),
'enable_tags' => false,
'tag_backgrounds' => array(),
'enable_post_types' => false,
'post_type_backgrounds' => array(),
'fallback_color' => '#ffffff',
'transition_enabled' => true,
'transition_duration' => '0.5s'
)plugins_loaded: Load text domainadmin_enqueue_scripts: Load admin CSS/JSwp_enqueue_scripts: Load frontend CSSadmin_menu: Add settings pageadmin_init: Register settingswp_head: Inject background CSSinit: Start PHP session (if needed)
plugin_action_links_{basename}: Add settings link
yt_rbg_preview_background: Generate random previewyt_rbg_upload_image: Handle image uploads
// Daily background (consistent per day)
$seed = current_time('Ymd'); // e.g., 20250118
mt_srand($seed);
$index = array_rand($backgrounds);
// Session background (consistent per visitor)
if (!isset($_SESSION['yt_rbg_seed'])) {
$_SESSION['yt_rbg_seed'] = time();
}
mt_srand($_SESSION['yt_rbg_seed']);
// Every load (truly random)
// No seed - uses default randomnessThe plugin injects CSS directly into <head>:
<!-- Random Background Generator -->
<style id="yt-rbg-inline-css">
body {
background-color: #3498db !important;
transition: background-color 0.5s ease, background-image 0.5s ease;
}
</style>For images:
body {
background-image: url(image.jpg) !important;
background-size: cover !important;
background-position: center center !important;
background-repeat: no-repeat !important;
background-attachment: fixed !important;
}// Category archive page
if (is_category()) {
$term_id = get_queried_object_id();
// Use category-specific background
}
// Single post with category
if (is_single()) {
$categories = get_the_category();
foreach ($categories as $category) {
// Check for category-specific background
}
}- Capability Checks:
manage_optionsfor settings - Nonce Verification: All AJAX requests
- Input Sanitization:
sanitize_hex_color()for color valuesesc_url_raw()for image URLssanitize_text_field()for text inputswp_strip_all_tags()for custom CSS
- Output Escaping:
esc_attr()for CSS attributesesc_url()for image URLsesc_html()for text display
- Array Validation: Type checking for arrays
- XSS Prevention: Proper HTML filtering
- Database: 1 option entry (5-50 KB depending on content)
- HTTP Requests: 0 (inline CSS injection)
- Memory: < 100 KB
- Frontend Impact: +1-2ms (CSS generation)
- Admin Pages: +100-150ms (CSS/JS only on settings page)
- Frontend: +5-10ms (background selection and CSS generation)
- Session Mode: +1ms (session check only)
- No External Files: CSS injected inline
- Conditional Loading: Admin assets only on settings page
- Efficient Selection: O(1) random selection
- Caching: Session/daily modes reduce computation
- Minimal DOM Impact: Single style tag injection
Not directly. Add solid colors and use Custom CSS field:
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}No, backgrounds change on page load only. For dynamic changes, you'd need custom JavaScript.
Yes, if you set the Target Element to the builder's container (e.g., .elementor-page, .fl-builder).
Not built-in. Consider using Custom CSS with :not() selector or conditional logic via child theme.
All web formats: JPG, PNG, GIF, WebP, SVG.
- Desktop: 1920x1080px or larger
- Mobile-friendly: 1200x800px minimum
- File size: Under 500KB for performance
Yes, paste any image URL in the category/tag background value field.
Yes, CSS is generated server-side on each request before caching.
Not directly. Use Custom CSS with media queries:
@media (max-width: 768px) {
body { background-color: #specific-color !important; }
}The Fallback Color is used (default: white).
Causes:
- Plugin not enabled
- No backgrounds configured
- Target element incorrect
- Theme CSS overriding
Solutions:
- Check "Enable Random Backgrounds" is checked
- Add at least one color or image
- Verify Target Element selector
- Increase CSS specificity or add
!important
Causes:
- Change Frequency set to Daily or Session
- Caching plugin caching CSS
- Only one background configured
Solutions:
- Change frequency to "Every page load"
- Clear cache
- Add more backgrounds to pool
Causes:
- Invalid image URL
- HTTPS/HTTP mismatch
- Image file deleted
- CORS issues (external images)
Solutions:
- Verify image URLs are accessible
- Ensure HTTPS for secure sites
- Re-upload images to Media Library
- Use images from same domain
Causes:
- Image Size set to Contain or Auto
- Target Element too small
- Theme has wrapper elements
Solutions:
- Set Image Size to "Cover"
- Change Target Element to
body - Adjust CSS with Custom CSS field
Causes:
- Category backgrounds not enabled
- Viewing archive vs. single post
- Wrong category ID
Solutions:
- Enable "Category Backgrounds" setting
- Check if on category archive or single post
- Verify category has background assigned
Causes:
- Large image files
- Too many images
- Transition effects
Solutions:
- Optimize images (compress, resize)
- Limit to 10-20 backgrounds
- Disable transitions
- Use colors instead of images
Causes:
- Sessions not started
- Session data not persisting
- Hosting restrictions
Solutions:
- Check PHP sessions enabled
- Contact hosting support
- Use "Daily" mode instead
Do:
- Optimize images (compress, WebP format)
- Limit to 10-20 backgrounds
- Use solid colors when possible
- Set reasonable transition duration (0.3-1s)
Don't:
- Use huge image files (>1MB)
- Add 50+ backgrounds
- Enable transitions on slow sites
- Target multiple elements
Do:
- Choose colors with good contrast for text
- Use cohesive color palettes
- Test backgrounds with actual content
- Consider mobile viewports
Don't:
- Use clashing colors
- Forget about text readability
- Use busy patterns that distract
- Ignore mobile users
Do:
- Use Session mode for consistency
- Provide visual coherence
- Test with different content types
- Consider accessibility
Don't:
- Change too frequently (jarring)
- Use extreme contrasts
- Forget color-blind users
- Ignore page load impact
Do:
- Match backgrounds to content themes
- Use category backgrounds strategically
- Keep branding consistent
- Test with real users
Don't:
- Randomize on every micro-interaction
- Conflict with brand colors
- Overwhelm content
- Use without purpose
- Plugin settings (colors, images, configuration)
- Session data (if Session mode enabled)
- No user-specific data
- No tracking or analytics
When Session mode enabled:
- PHP session stores random seed
- Session ID stored in browser cookie
- Cleared when browser closes
- No personal data collected
- No personal data collected
- Session cookies are functional only
- No external API calls
- No user tracking
- No analytics
When you delete the plugin:
- Plugin settings deleted from database
- Session data cleared
- Inline CSS removed from pages
- Backgrounds revert to theme defaults
- No residual files
Note: Backgrounds are non-permanent, removed immediately on plugin deletion.
- Initial release
- Random color backgrounds
- Random image backgrounds
- Mixed mode (colors + images)
- Change frequency options (every load, daily, session)
- Category-specific backgrounds
- Tag-specific backgrounds (optional)
- Post type backgrounds (optional)
- Color picker integration
- Media library integration
- Image display settings (size, position, repeat, attachment)
- Live preview generator
- Smooth transitions
- Custom target element
- Fallback color
- Custom CSS field
- Translation ready
- Mobile responsive admin
Potential future features:
- Time-based backgrounds (morning, afternoon, evening)
- Weather-based backgrounds (API integration)
- User preference selection
- Background scheduler (specific dates)
- Video backgrounds
- Animated gradients
- Multiple element targeting
- Background templates library
- Import/export settings
- Background analytics
- A/B testing
- Conditional logic builder
- Background overlays
- Text color auto-adjustment
- Blur effects
- Parallax intensity control
- PHP: 1,024 lines
- CSS: 584 lines
- JS: 456 lines
- Total: 2,064 lines
add_filter('yt_rbg_background', function($background) {
// Custom logic to modify background
if (is_front_page()) {
return array(
'type' => 'color',
'value' => '#custom-color'
);
}
return $background;
});add_filter('yt_rbg_css', function($css, $background) {
// Add custom CSS rules
$css .= ' body::before { content: ""; }';
return $css;
}, 10, 2);add_filter('yt_rbg_background_types', function($types) {
$types['gradient'] = __('Gradients', 'textdomain');
return $types;
});add_filter('yt_rbg_available_backgrounds', function($backgrounds, $type) {
// Filter backgrounds based on custom logic
return array_filter($backgrounds, 'my_custom_filter');
}, 10, 2);Access JavaScript functions:
// Get manager instance
var manager = window.RandomBackgroundGenerator;
// Generate preview
manager.generatePreview();
// Get random background
var bg = manager.getRandomBackground();
// Apply background to element
manager.applyBackgroundToPreview(bg);
// Export settings
manager.exportSettings();PHP Actions:
yt_rbg_before_css_injection: Before CSS injectedyt_rbg_after_css_injection: After CSS injectedyt_rbg_settings_saved: After settings saved
PHP Filters:
yt_rbg_background: Modify selected backgroundyt_rbg_css: Modify generated CSSyt_rbg_target_element: Modify target selectoryt_rbg_available_backgrounds: Filter background pool
Follow WordPress Coding Standards:
# PHP Code Sniffer
phpcs --standard=WordPress yt-random-background-generator.php
# JavaScript linting
eslint yt-random-background-generator.js
# CSS linting
stylelint yt-random-background-generator.cssFor issues, questions, or feature requests:
GPL v2 or later
Krasen Slavov
- Website: https://krasenslavov.com
- GitHub: @krasenslavov
Add dynamic visual excitement to your WordPress site with random backgrounds!