Creating Custom Performance Optimizations

Disable Unnecessary WordPress Features

Add these functions to your child theme’s functions.php file to remove features that may impact performance:

// Disable WordPress emoji scripts and styles
function digifusion_child_disable_emojis() {
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );
    remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
    remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
    remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
}
add_action( 'init', 'digifusion_child_disable_emojis' );

// Remove unnecessary WordPress head tags
function digifusion_child_cleanup_head() {
    remove_action( 'wp_head', 'wp_generator' );
    remove_action( 'wp_head', 'wp_shortlink_wp_head' );
    remove_action( 'wp_head', 'wlwmanifest_link' );
    remove_action( 'wp_head', 'rsd_link' );
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head' );
}
add_action( 'init', 'digifusion_child_cleanup_head' );

// Disable WordPress heartbeat on frontend
function digifusion_child_disable_heartbeat() {
    if ( ! is_admin() ) {
        wp_deregister_script( 'heartbeat' );
    }
}
add_action( 'wp_enqueue_scripts', 'digifusion_child_disable_heartbeat' );

Optimize Asset Loading

Defer Non-Critical JavaScript

// Defer JavaScript loading for better performance
function digifusion_child_defer_scripts( $tag, $handle, $src ) {
    // Scripts to defer (add more as needed)
    $defer_scripts = array(
        'digifusion-app',
        'comment-reply',
        'wp-embed'
    );
    
    if ( in_array( $handle, $defer_scripts ) ) {
        return str_replace( ' src', ' defer src', $tag );
    }
    
    return $tag;
}
add_filter( 'script_loader_tag', 'digifusion_child_defer_scripts', 10, 3 );

// Preload critical assets
function digifusion_child_preload_assets() {
    // Preload theme stylesheet
    echo '<link rel="preload" href="' . get_stylesheet_uri() . '" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">';
    
    // Preload critical fonts
    echo '<link rel="preload" href="' . get_stylesheet_directory_uri() . '/assets/fonts/primary-font.woff2" as="font" type="font/woff2" crossorigin>';
}
add_action( 'wp_head', 'digifusion_child_preload_assets', 1 );

Database Query Optimization

// Limit post revisions
function digifusion_child_limit_revisions( $num, $post ) {
    return 3;
}
add_filter( 'wp_revisions_to_keep', 'digifusion_child_limit_revisions', 10, 2 );

// Optimize database queries for widgets
function digifusion_child_optimize_widget_queries() {
    // Disable widgets on non-widget areas to reduce queries
    if ( ! is_active_sidebar( 'sidebar-1' ) && ! is_singular() ) {
        remove_action( 'wp_head', '_wp_render_title_tag', 1 );
    }
}
add_action( 'wp', 'digifusion_child_optimize_widget_queries' );

// Cache heavy queries
function digifusion_child_get_popular_posts( $limit = 5 ) {
    $cache_key = 'digifusion_popular_posts_' . $limit;
    $popular_posts = wp_cache_get( $cache_key );
    
    if ( false === $popular_posts ) {
        $popular_posts = get_posts( array(
            'numberposts' => $limit,
            'meta_key' => 'post_views_count',
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
            'post_status' => 'publish'
        ) );
        
        wp_cache_set( $cache_key, $popular_posts, '', 3600 ); // Cache for 1 hour
    }
    
    return $popular_posts;
}

Image Optimization

// Add SVG support
function digifusion_child_add_svg_support( $mime_types ) {
    $mime_types['svg'] = 'image/svg+xml';
    return $mime_types;
}
add_filter( 'upload_mimes', 'digifusion_child_add_svg_support' );

// Lazy load images
function digifusion_child_add_lazy_loading( $attr, $attachment, $size ) {
    if ( ! is_admin() ) {
        $attr['loading'] = 'lazy';
        $attr['decoding'] = 'async';
    }
    return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'digifusion_child_add_lazy_loading', 10, 3 );

// Optimize image sizes
function digifusion_child_custom_image_sizes() {
    // Add optimized image sizes
    add_image_size( 'optimized-thumbnail', 300, 200, true );
    add_image_size( 'optimized-medium', 600, 400, true );
}
add_action( 'after_setup_theme', 'digifusion_child_custom_image_sizes' );

Critical CSS Implementation

Create a file assets/css/critical.css in your child theme:

/* Critical above-the-fold styles */
body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
}

.site-header {
    position: relative;
    z-index: 1000;
}

.site-main {
    min-height: 50vh;
}

.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

Then add this to functions.php:

// Inline critical CSS
function digifusion_child_inline_critical_css() {
    $critical_css_file = get_stylesheet_directory() . '/assets/css/critical.css';
    
    if ( file_exists( $critical_css_file ) ) {
        $critical_css = file_get_contents( $critical_css_file );
        echo '<style id="critical-css">' . $critical_css . '</style>';
    }
}
add_action( 'wp_head', 'digifusion_child_inline_critical_css', 1 );

Resource Hints and Prefetching

// Add resource hints for better performance
function digifusion_child_resource_hints( $urls, $relation_type ) {
    switch ( $relation_type ) {
        case 'dns-prefetch':
            $urls[] = '//fonts.googleapis.com';
            $urls[] = '//fonts.gstatic.com';
            break;
            
        case 'preconnect':
            $urls[] = array(
                'href' => 'https://fonts.googleapis.com',
                'crossorigin',
            );
            break;
            
        case 'prefetch':
            if ( is_front_page() ) {
                $urls[] = get_permalink( get_option( 'page_for_posts' ) );
            }
            break;
    }
    
    return $urls;
}
add_filter( 'wp_resource_hints', 'digifusion_child_resource_hints', 10, 2 );

Advanced Caching Functions

// Custom transient caching for expensive operations
function digifusion_child_get_cached_menu( $location ) {
    $cache_key = 'digifusion_menu_' . $location;
    $menu_html = get_transient( $cache_key );
    
    if ( false === $menu_html ) {
        ob_start();
        wp_nav_menu( array(
            'theme_location' => $location,
            'container' => false,
            'echo' => false
        ) );
        $menu_html = ob_get_clean();
        
        set_transient( $cache_key, $menu_html, 12 * HOUR_IN_SECONDS );
    }
    
    return $menu_html;
}

// Clear menu cache when menus are updated
function digifusion_child_clear_menu_cache() {
    delete_transient( 'digifusion_menu_primary' );
    delete_transient( 'digifusion_menu_footer' );
}
add_action( 'wp_update_nav_menu', 'digifusion_child_clear_menu_cache' );

Performance Monitoring

Create assets/js/performance-monitor.js:

// Performance monitoring script
(function() {
    'use strict';
    
    // Monitor Core Web Vitals
    function measurePerformance() {
        if ('performance' in window && 'getEntriesByType' in performance) {
            // Measure page load time
            window.addEventListener('load', function() {
                const navigation = performance.getEntriesByType('navigation')[0];
                const loadTime = navigation.loadEventEnd - navigation.fetchStart;
                
                console.log('Page Load Time:', loadTime + 'ms');
                
                // Send to analytics if needed
                if (window.gtag) {
                    gtag('event', 'timing_complete', {
                        name: 'load',
                        value: Math.round(loadTime)
                    });
                }
            });
            
            // Measure First Contentful Paint
            const observer = new PerformanceObserver(function(list) {
                for (const entry of list.getEntries()) {
                    if (entry.name === 'first-contentful-paint') {
                        console.log('FCP:', entry.startTime + 'ms');
                    }
                }
            });
            
            observer.observe({entryTypes: ['paint']});
        }
    }
    
    // Initialize performance monitoring
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', measurePerformance);
    } else {
        measurePerformance();
    }
})();

Add this to enqueue the performance monitor:

// Enqueue performance monitoring (only in development)
function digifusion_child_enqueue_performance_monitor() {
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
        wp_enqueue_script(
            'digifusion-performance-monitor',
            get_stylesheet_directory_uri() . '/assets/js/performance-monitor.js',
            array(),
            wp_get_theme()->get( 'Version' ),
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'digifusion_child_enqueue_performance_monitor' );