How to Create a WordPress plugin for page loading times and SEO.This example includes features such as image lazy loading, browser caching, and minification of CSS and JavaScript.
<?php
/**
* Plugin Name: SpeedOptimize
* Description: A simple WordPress plugin to improve page loading times and SEO.
* Version: 1.0
* Author: Your Name
*/
// Enqueue the optimization scripts
function speed_optimize_enqueue_scripts() {
// Enqueue optimized scripts
wp_enqueue_script('optimized-scripts', plugin_dir_url(__FILE__) . 'js/optimized-scripts.js', array('jquery'), '1.0', true);
// Add async and defer attributes to scripts
add_filter('script_loader_tag', function ($tag, $handle) {
if ('optimized-scripts' !== $handle) {
return $tag;
}
return str_replace(' src', ' async defer src', $tag);
}, 10, 2);
}
add_action('wp_enqueue_scripts', 'speed_optimize_enqueue_scripts');
// Enable image lazy loading
function speed_optimize_enable_lazy_loading($content) {
return 'loading="lazy" ' . $content;
}
add_filter('the_content', 'speed_optimize_enable_lazy_loading');
// Enable browser caching
function speed_optimize_browser_caching() {
if (!is_admin()) {
// Set browser caching for 1 week
header('Cache-Control: public, max-age=' . 604800);
}
}
add_action('init', 'speed_optimize_browser_caching');
// Minify CSS and JavaScript files
function speed_optimize_minify_assets() {
if (!is_admin()) {
// Minify CSS
wp_register_style('minified-style', plugin_dir_url(__FILE__) . 'css/minified-style.css');
wp_enqueue_style('minified-style');
// Minify JavaScript
wp_register_script('minified-script', plugin_dir_url(__FILE__) . 'js/minified-script.js', array(), '1.0', true);
wp_enqueue_script('minified-script');
}
}
add_action('wp_enqueue_scripts', 'speed_optimize_minify_assets');