# WordPress Optimization Guide


**Last Updated:** 2025-11-20

## Overview

The performance optimization system is **WordPress-aware** and handles blog pages (`/insights/*`) differently from static PHP pages to ensure we don't break the WordPress CMS setup.

## WordPress vs Static Pages

### Blog Pages (WordPress)

- **Path Pattern**: `/insights/*` (except `/insights/dienstplan` and `/insights/zeiterfassung` which are pillar PHP pages)
- **Management**: Managed by WordPress CMS
- **Optimization Method**: WordPress hooks and filters (via `wordpress-optimization-hooks.php`)
- **Files We Can Modify**: Theme `functions.php`, theme templates, CSS/JS files
- **Files We Should NOT Touch**: Core WordPress files, `wp-config.php`, database

### Static PHP Pages

- **Path Pattern**: All other pages (product, comparison, tools, industry, etc.)
- **Management**: Direct PHP files in `v2/pages/`
- **Optimization Method**: Direct file manipulation with backups
- **Files We Can Modify**: Any PHP file in `v2/pages/`, CSS/JS in `v2/css/` and `v2/js/`

## WordPress Optimization Setup

### Step 1: Include Optimization Hooks

Add to your WordPress theme's `functions.php`:

```php
// Include Ordio performance optimization hooks
require_once get_template_directory() . '/../../v2/scripts/wordpress-optimization-hooks.php';
```

**OR** if the theme is in a different location:

```php
// Adjust path as needed
require_once ABSPATH . 'v2/scripts/wordpress-optimization-hooks.php';
```

### Step 2: Verify Hooks Are Active

The hooks file (`v2/scripts/wordpress-optimization-hooks.php`) includes:

- **Image Optimization**: WebP support, lazy loading, responsive images
- **CSS Optimization**: Deferred loading, minification support
- **JavaScript Optimization**: Defer/async attributes
- **Resource Hints**: Preload, preconnect
- **Font Optimization**: font-display support
- **HTML Minification**: Output buffering for HTML compression
- **Feature Disabling**: Removes unnecessary WordPress features (emojis, etc.)

### Step 3: Test Blog Pages

After enabling hooks, test a blog page:

```bash
php v2/scripts/optimize-images.php --url="https://www.ordio.com/insights/ratgeber/example" --recommendations='[{"id":"modern-image-formats"}]'
```

The script will detect it's a WordPress page and return instructions for manual theme modifications if needed.

## Optimization Scripts

All optimization scripts automatically detect WordPress vs static pages:

### Image Optimization

```bash
php v2/scripts/optimize-images.php --url="URL" --recommendations="JSON"
```

**WordPress Pages**: Returns hook-based instructions
**Static Pages**: Directly modifies PHP files with backups

### Asset Optimization

```bash
php v2/scripts/optimize-assets.php --url="URL" --recommendations="JSON"
```

**WordPress Pages**: Uses WordPress hooks (already in `wordpress-optimization-hooks.php`)
**Static Pages**: Updates asset references to minified versions

### HTML Optimization

```bash
php v2/scripts/optimize-html.php --url="URL" --recommendations="JSON"
```

**WordPress Pages**: Requires theme template modifications (manual)
**Static Pages**: Directly optimizes HTML structure

### Resource Loading

```bash
php v2/scripts/optimize-resource-loading.php --url="URL" --recommendations="JSON"
```

**WordPress Pages**: Uses WordPress hooks (already in `wordpress-optimization-hooks.php`)
**Static Pages**: Adds preload/preconnect hints directly

## Auto-Fix System

The auto-fix system (`v2/scripts/auto-fix-performance.php`) automatically applies safe optimizations:

```bash
php v2/scripts/auto-fix-performance.php --url="URL" --recommendations="JSON" --risk-level="low"
```

**Risk Levels**:

- `low`: Only safest fixes (minification, meta tags)
- `medium`: Includes image optimization, resource hints
- `high`: Includes HTML structure changes
- `all`: All available fixes

**WordPress Pages**: Applies fixes via hooks where possible, flags manual steps
**Static Pages**: Directly applies fixes with automatic backups

## Batch Processing

Process multiple pages efficiently:

```bash
php v2/scripts/batch-optimize.php --tasks="JSON" --options='{"risk_level":"low","validate_after":true}'
```

The batch processor automatically:

- Groups tasks by type for efficiency
- Handles WordPress vs static pages appropriately
- Validates fixes after application
- Rolls back on validation failure

## WordPress Theme Files We Can Modify

### Safe to Modify

- `wp-content/themes/{theme}/functions.php` - Add hooks
- `wp-content/themes/{theme}/style.css` - CSS optimizations
- `wp-content/themes/{theme}/*.php` - Template files (with caution)
- `wp-content/themes/{theme}/assets/` - CSS/JS files

### Should NOT Modify

- `wp-config.php` - WordPress core configuration
- `wp-admin/` - WordPress admin files
- `wp-includes/` - WordPress core files
- Database directly (use WordPress APIs)

## Manual WordPress Optimizations

Some optimizations require manual theme modifications:

### 1. Image Optimization

Add to theme `functions.php`:

```php
// WebP support
add_filter('wp_get_attachment_image_src', 'ordio_convert_to_webp', 10, 4);

// Lazy loading
add_filter('wp_get_attachment_image_attributes', 'ordio_add_lazy_loading', 10, 3);
```

### 2. CSS/JS Optimization

The hooks file already handles:

- Deferred CSS loading
- Deferred JavaScript loading
- Minification support

### 3. Font Optimization

Add to theme CSS:

```css
@font-face {
  font-family: "YourFont";
  src: url("font.woff2") format("woff2");
  font-display: swap; /* Critical for performance */
}
```

## Validation

After applying optimizations, validate they work:

```bash
php v2/helpers/performance-fix-validator.php
```

Or use the validation functions:

- `validateImageOptimization($file)`
- `validateCSSMinification($file)`
- `testPageFunctionality($url)`
- `validateOptimizationFix($optimization, $url)`

## Rollback

If an optimization causes issues, rollback:

```bash
php -r "require 'v2/helpers/performance-rollback.php'; rollbackOptimization('optimization-id');"
```

Or via the helper:

```php
require_once 'v2/helpers/performance-rollback.php';
$result = rollbackOptimization($optimizationId);
```

## Best Practices

1. **Always Test**: Test optimizations on a staging site first
2. **Use Backups**: All static page optimizations create automatic backups
3. **WordPress Hooks**: Prefer hooks over direct file manipulation for blog pages
4. **Theme Updates**: Be aware that theme updates may overwrite customizations
5. **Child Themes**: Use child themes for WordPress customizations
6. **Monitor Impact**: Use the optimization tracker to monitor before/after performance

## Troubleshooting

### WordPress Hooks Not Working

1. Verify `wordpress-optimization-hooks.php` is included in `functions.php`
2. Check for PHP errors in WordPress debug log
3. Ensure theme is active
4. Clear WordPress cache if using caching plugins

### Static Page Optimizations Not Applying

1. Check file permissions
2. Verify backup directory is writable
3. Check for PHP errors in logs
4. Ensure file paths are correct

### Performance Not Improving

1. Re-run PageSpeed Insights to verify changes
2. Check browser cache (hard refresh)
3. Verify optimizations were actually applied
4. Review optimization recommendations for accuracy

## Integration with Dashboard

The performance dashboard automatically detects WordPress vs static pages and shows appropriate optimization options:

- **WordPress Pages**: Shows hook-based optimization status
- **Static Pages**: Shows direct file optimization status

Both types are tracked in the optimization history system.
