🧩 Module 12 – Plugin Security, Performance & Best Practices
In this final module, you’ll learn how to keep your WordPress plugin secure, fast, and reliable. We’ll cover sanitization, escaping, nonces, database safety, and performance tips.
Step 1 – Sanitize User Input
Always clean any data from users before saving to the database or displaying on screen.
$user_input = $_POST['username'] ?? '';
$clean_input = sanitize_text_field( $user_input );
// Example: Save safely
update_option( 'mfp_username', $clean_input );
Step 2 – Escape Output
When printing values on a page, escape them to prevent XSS (Cross-Site Scripting).
$name = get_option('mfp_username');
echo '<h3>Hello, ' . esc_html( $name ) . '!</h3>';
Step 3 – Use Nonces for Form Security
Nonces ensure only valid requests modify data.
<form method="post">
<?php wp_nonce_field( 'mfp_save_data', 'mfp_nonce' ); ?>
<input type="text" name="username">
<input type="submit" value="Save">
</form>
<?php
if ( isset($_POST['mfp_nonce']) && wp_verify_nonce($_POST['mfp_nonce'], 'mfp_save_data') ) {
$username = sanitize_text_field($_POST['username']);
update_option('mfp_username', $username);
echo '<p style="color:#00ffa3">Saved!</p>';
}
?>
Step 4 – Use Prepared Statements for SQL
Avoid building SQL queries with string concatenation — use the $wpdb->prepare() method.
global $wpdb;
$username = 'admin';
$results = $wpdb->get_results(
$wpdb->prepare( "SELECT * FROM {$wpdb->users} WHERE user_login = %s", $username )
);
Step 5 – Performance Tips
- ✅ Use
transientsto cache data from APIs or heavy DB queries. - ✅ Load scripts only when necessary using
admin_enqueue_scriptsconditions. - ✅ Use
filemtime()for cache-busting only when scripts truly change. - ✅ Avoid loading large CSS/JS on pages where your plugin isn’t used.
// Example: conditional script load
function myplugin_enqueue_scripts($hook) {
if ( $hook !== 'toplevel_page_myplugin' ) return;
wp_enqueue_script( 'myplugin-admin', plugin_dir_url(__FILE__) . 'admin.js', array('jquery'), filemtime(__FILE__), true );
}
add_action('admin_enqueue_scripts', 'myplugin_enqueue_scripts');
Step 6 – Follow Coding Standards
- Use
snake_casefor functions and variables. - Prefix everything (e.g.,
mfp_) to avoid name collisions. - Document your code with clear comments.
- Validate your plugin with the WordPress Plugin Check tool.
Step 7 – Prepare for Distribution
- Add
readme.txtwith description, version, author, and license. - Use proper folder structure (
includes/,assets/, etc.). - Provide translation support with
load_plugin_textdomain(). - Keep plugin lightweight – load only what’s needed.
🎯 Wrap-Up
Congratulations! You’ve now built a full-featured WordPress plugin suite — from login systems, AJAX, REST API, Gutenberg blocks, widgets, to now secure and performant production-ready plugins.
✔ Next Steps: publish your plugin to WordPress.org or your own GitHub repository!
No comments:
Post a Comment