WP Manifestindependent plugin directory
manifest / utilities / auto-permalink-regenerator

Auto Permalink Regenerator

Flushes rewrite rules hourly and after publishing new content to prevent 404 errors.

by SPARKWEB Studio · github.com/spkcd/auto-permalink-regenerator

★ 0stars
0forks

Install

No release zip yet. The repository archive installs, but the folder name will carry the branch suffix and updates will not flow:

wp plugin install https://github.com/spkcd/auto-permalink-regenerator/archive/refs/heads/main.zip

A WordPress plugin that automatically flushes rewrite rules to prevent 404 errors on posts and pages. This plugin helps maintain proper URL structure by scheduling regular permalink regeneration and responding to content changes.

Features

Core Functionality

  • Hourly Cron Job: Automatically flushes rewrite rules every hour via auto_regenerate_permalinks_hourly cron hook
  • Publish Hooks: Automatically flushes rewrite rules when new posts or pages are published
  • 404 Spike Detection: Monitors 404 errors and auto-flushes when 5+ unique 404s occur in 10 minutes
  • Smart .htaccess Management: Detects missing or corrupted .htaccess files and regenerates them with proper WordPress rules
  • Backup System: Creates timestamped backups before modifying .htaccess files

Admin Interface

  • Settings Page: Configure plugin behavior from WordPress admin (Settings > Permalink Regenerator)
  • Tools Page: Dedicated tools interface with manual flush functionality (Tools > Permalink Regenerator)
  • Manual Flush: Trigger immediate rewrite rule flush with secure form submission
  • 404 Error Monitoring: Real-time tracking of 404 errors with automatic spike detection
  • Dashboard Widget: "Permalink Health Monitor" widget with real-time status and quick actions
  • Site Health Integration: Native WordPress Site Health dashboard integration with intelligent status monitoring
  • Diagnostics Screen: Comprehensive diagnostic tools under Tools > Permalink Diagnostics
  • Email Notifications: Automatic email alerts for manual flushes, 404 spikes, and .htaccess issues
  • Comprehensive Logging: Every flush_rewrite_rules() call logged to database with duplicate prevention
  • Activity Management: View and clear activity logs with admin controls
  • Status Monitoring: View next scheduled flush time and system status
  • Permission Checking: Real-time file permission status for .htaccess

Safety Features

  • No Page Load Impact: Never flushes rewrite rules on init to avoid performance issues
  • Permission Validation: Checks file permissions before attempting .htaccess modifications
  • Rate Limiting: .htaccess checks are limited to once per hour to prevent performance degradation
  • Comprehensive Logging: Every flush operation logged with duplicate prevention (1-minute window)
  • Error Logging: Dual logging system (database + WordPress error log)
  • Admin Notices: User-friendly notifications for permission issues and status updates

Installation

  1. Download the plugin files
  2. Upload auto-permalink-regenerator.php to your /wp-content/plugins/auto-permalink-regenerator/ directory
  3. Activate the plugin through the 'Plugins' menu in WordPress
  4. Configure settings via Settings > Permalink Regenerator

Configuration

Settings Page

Navigate to Settings > Permalink Regenerator to configure:

  • Flush on Publish: Enable/disable automatic flush when posts/pages are published
  • Check .htaccess: Enable/disable automatic .htaccess monitoring and repair
  • Email Notifications: Enable/disable email alerts for permalink actions

Tools Page

Navigate to Tools > Permalink Regenerator for:

  • Manual Flush: "Manually Regenerate Permalinks" button with security validation
  • Activity Log: View last 10 permalink regeneration activities with timestamps (reverse chronological)
  • 404 Error Dashboard: Monitor current 404 count, auto-flush status, and recent 404 errors
  • Log Management: "Clear All Logs" and "Clear 404 Logs" buttons with confirmation prompts
  • Plugin Information: Version, next scheduled flush, and system configuration details

Diagnostics Page

Navigate to Tools > Permalink Diagnostics for:

  • System Health Checks: 8 automated diagnostic tests with ✅ PASSED / ❌ FAILED status:
    • Cron job scheduling verification
    • .htaccess file writability check
    • .htaccess backup existence validation
    • Database table integrity verification
    • Recent log entries analysis (minimum 3 in 30 days)
    • Recent flush activity monitoring (within 24 hours)
    • Email function availability testing
    • Site Health integration verification
  • Diagnostic Actions: Interactive buttons with security validation:
    • "Run Test Flush" - Performs test flush with logging
    • "Send Test Email" - Tests email notification system
    • "Reschedule Cron" - Resets cron job scheduling
  • Advanced Logs: Collapsible section showing last 10 flush logs with timestamps and trigger types

Manual Actions

  • Settings Page: AJAX-powered flush with real-time status updates
  • Tools Page: Form-based flush with success message and activity logging

How It Works

Activation

  1. Creates custom database table wp_apr_logs for activity logging
  2. Schedules hourly cron job using wp_schedule_event()
  3. Performs initial rewrite rule flush with database logging
  4. Checks .htaccess file integrity

Deactivation

  1. Removes scheduled cron job using wp_unschedule_event()
  2. Cleans up temporary notices and transients

Runtime Behavior

  1. Hourly Flush: Cron job runs flush_rewrite_rules() every hour with database logging
  2. Publish Events: Hooks into publish_post and publish_page actions with activity logging
  3. 404 Spike Detection: Monitors unique 404 errors and auto-flushes after threshold (5 in 10 minutes)
  4. Manual Flush: Secure form-based flush via Tools page with success messages
  5. htaccess Monitoring: Checks file integrity hourly (admin area only)
  6. Backup Creation: Creates .htaccess.backup.YYYY-MM-DD-HH-MM-SS before modifications
  7. Comprehensive Logging: Every flush operation logged to wp_apr_logs with duplicate prevention
  8. 404 Error Tracking: Logs individual 404 errors with URL, referrer, and timestamp data
  9. Cooldown Protection: 15-minute cooldown after auto-flush prevents infinite loops
  10. Email Notifications: Automatic email alerts sent to site administrator for all permalink actions
  11. Site Health Monitoring: Real-time status reporting in WordPress Site Health dashboard
  12. Dashboard Widget: Admin dashboard widget with real-time statistics and quick actions

File Structure

auto-permalink-regenerator/
├── auto-permalink-regenerator.php  # Main plugin file
├── README.md                       # Documentation
└── CHANGELOG.md                    # Version history

Requirements

  • WordPress 4.0 or higher
  • PHP 5.6 or higher
  • Write permissions for .htaccess file (optional, for automatic repair)

Compatibility

  • Works with all WordPress themes
  • Compatible with caching plugins
  • Multisite compatible
  • No conflicts with other permalink plugins

Troubleshooting

Common Issues

Cron Job Not Running

  • Check if WordPress cron is enabled
  • Verify server supports cron jobs
  • Use WP-Cron Control plugin to debug

htaccess Permission Errors

  • Set .htaccess file permissions to 644
  • Ensure WordPress directory has write permissions
  • Check with hosting provider about file permission restrictions

Manual Flush Not Working

  • Verify user has administrator privileges
  • Check browser console for JavaScript errors
  • Ensure WordPress AJAX is functioning

Debug Information

The plugin logs all activities to the WordPress error log. Enable WordPress debugging to view:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

Email Notifications

Email Triggers

The plugin sends automatic email notifications for:

  • Manual Flush: When administrators trigger permalink regeneration manually
  • 404 Spike Detection: When automatic flush occurs due to 404 error threshold
  • .htaccess Rewrite: When .htaccess file is automatically regenerated (success/failure)

Email Customization

Developers can customize emails using these filters:

// Change email recipient
add_filter('apr_notification_email', function($email) {
    return 'admin@example.com';
});

// Customize email subject
add_filter('apr_notification_subject', function($subject, $trigger, $status) {
    return "[Custom] Permalink Action: $trigger";
}, 10, 3);

// Modify email body
add_filter('apr_notification_body', function($body, $trigger, $status, $info) {
    return $body . "\n\nCustom footer content";
}, 10, 4);

// Customize email headers
add_filter('apr_notification_headers', function($headers, $trigger, $status) {
    $headers[] = 'Reply-To: support@example.com';
    return $headers;
}, 10, 3);

Disable Email Notifications

To disable email notifications:

  1. Uncheck "Email Notifications" in plugin settings, OR
  2. Use a filter to return false:
    add_filter('apr_notification_email', '__return_false');

Site Health Integration

Automatic Status Monitoring

The plugin integrates with WordPress Site Health (Tools > Site Health) to provide real-time permalink status monitoring:

Status Levels

  • ✅ Good Status: "Permalinks recently flushed"

    • Displayed when permalinks were flushed within the last 24 hours
    • Indicates healthy permalink system
    • Badge color: Green
  • ⚠️ Recommended Action: "Permalinks may be outdated"

    • Shown when no flush has occurred in 72+ hours
    • Suggests manual flush if experiencing 404 errors
    • Badge color: Orange
  • ❌ Critical Status: "Recent 404 error spike detected"

    • Triggered when 404 spike detected in last 24 hours
    • Indicates potential permalink issues requiring attention
    • Badge color: Red
  • ℹ️ Normal Status: "Permalink system functioning normally"

    • Default state when system is monitoring normally
    • Badge color: Blue

Site Health Information

Each status includes:

  • Detailed Description: Explains current permalink health
  • Last Flush Information: When permalinks were last regenerated
  • Action Links: Direct access to plugin dashboard and WordPress settings
  • Contextual Recommendations: Specific guidance based on current status

Access Site Health

Navigate to Tools > Site Health in your WordPress admin to view the Auto Permalink Regenerator status alongside other site health checks.

Dashboard Widget

Permalink Health Monitor

The plugin adds a "Permalink Health Monitor" widget to your WordPress admin dashboard, providing administrators with instant access to permalink status and actions.

Widget Content

  • Quick Statistics: Visual grid showing flushes this week and 404 errors in last 24 hours
  • Last Flush Information: When permalinks were last regenerated with human-readable timing
  • Trigger Source: Shows what caused the last flush (manual, cron, 404 spike, etc.)
  • System Status: Overall permalink health with color-coded indicators
  • .htaccess Status: File availability and accessibility status

Quick Actions

  • Manual Flush: One-click permalink regeneration with AJAX feedback
  • View .htaccess: Modal overlay displaying current .htaccess file content
  • Full Dashboard: Direct link to complete plugin dashboard

Status Indicators

  • ✅ Green: Healthy status (recent flush, no issues)
  • ⚠️ Orange: Warning status (outdated flushes, some 404s)
  • ❌ Red: Critical status (404 spikes, missing files)

Administrative Access

  • Capability Requirement: Only users with manage_options capability can see the widget
  • High Priority: Widget appears prominently at the top of the dashboard
  • Mobile Responsive: Optimized layout for all screen sizes

Widget Features

  • Real-time Data: Current statistics pulled from plugin database
  • AJAX Integration: Actions performed without page reload
  • Professional Styling: WordPress-native design with consistent theming
  • Secure Operations: All actions protected with nonces and capability checks

Hooks and Filters

Actions Used

  • register_activation_hook - Plugin activation setup
  • register_deactivation_hook - Plugin cleanup
  • auto_regenerate_permalinks_hourly - Custom cron hook
  • publish_post - Post publication trigger
  • publish_page - Page publication trigger
  • admin_menu - Admin menu integration
  • admin_init - Admin initialization
  • admin_notices - Admin notifications
  • wp_ajax_manual_flush_permalinks - AJAX handler
  • template_redirect - 404 error detection
  • site_status_tests - Site Health integration
  • wp_dashboard_setup - Dashboard widget integration

WordPress Functions Used

  • flush_rewrite_rules() - Core rewrite rule flushing
  • wp_schedule_event() - Cron job scheduling
  • wp_next_scheduled() - Cron job status checking
  • wp_unschedule_event() - Cron job removal
  • wp_mail() - Email notification delivery
  • human_time_diff() - User-friendly time display for Site Health

Security

  • CSRF protection via WordPress nonces
  • Capability checks for admin functions
  • Input sanitization and output escaping
  • Secure AJAX implementations
  • File permission validation

Performance

The plugin is designed for minimal performance impact:

  • No database queries on frontend
  • Cron jobs run in background
  • Rate-limited .htaccess checks
  • Efficient option caching
  • No init hook usage

Support

For issues or feature requests:

  1. Check the troubleshooting section
  2. Enable WordPress debugging
  3. Review error logs
  4. Contact SPARKWEB Studio support

License

This plugin is released under the GPL v2 or later license.

Author

SPARKWEB Studio
Website: https://sparkwebstudio.com

Version History

See CHANGELOG.md for detailed version history and updates.