10 WordPress Code Snippets Every Developer Should Save

10 essential WordPress PHP snippets covering performance, security, and admin customization. Disable emojis, custom login URL, role-based redirects, limit login attempts, defer scripts, and more - all without plugins.

Every WordPress developer builds up a personal library of snippets over time - small blocks of PHP that solve common problems without a plugin. These are the snippets worth keeping. They cover performance, security, user experience, and developer utility. Each one is a direct functions.php or must-use plugin addition that works on any WordPress site without dependencies.

All snippets are collected into a single GitHub Gist so you can save, fork, and reference them without losing the context of where they belong.


1. Disable WordPress Emojis

WordPress loads an emoji detection script and stylesheet on every page - even sites that never use emojis in content. This adds two extra HTTP requests on every page load. Disable it completely with this snippet. It removes all emoji-related scripts, styles, DNS prefetch hints, and the TinyMCE plugin.

Add to functions.php or a must-use plugin. Verify by loading your site and checking the page source - the emoji script and stylesheet tags should be absent.


2. Custom Login URL

The default wp-login.php URL is the first thing bots attack. Changing the login URL reduces automated brute-force attempts without affecting legitimate users. This snippet moves the login form to a custom URL and returns a 404 for the default wp-login.php to avoid revealing that WordPress is running behind the site.

Change the CUSTOM_LOGIN_SLUG constant to your preferred URL segment. After activating, bookmark the new URL and test it in a private browser window before logging out. Note: this is security through obscurity - use with strong passwords and two-factor authentication, not as a replacement for them.


3. Redirect After Login Based on Role

WordPress redirects all users to the dashboard after login by default. For sites with editors, authors, and customers who never need the dashboard, this is confusing. This snippet redirects users to different pages based on their role: admins go to the dashboard, editors to the posts list, shop customers to their account page.

Customize the redirect URLs per role to match your site structure. Add additional roles as needed following the same pattern.


4. Custom Excerpt Length and Read More Text

WordPress auto-excerpts are 55 words long and end with “[...]”. Both are customizable. This snippet changes the excerpt length to 30 words (better for card-based layouts) and replaces the ugly “[...]” with a proper “Read more” link.

The excerpt length in the first function is in words, not characters. Adjust EXCERPT_LENGTH to suit your design. The read more link uses the post permalink so it works correctly with archives and taxonomy pages.


5. Remove Admin Bar for Non-Admins

The WordPress admin bar shows on the front end for all logged-in users. For subscriber-level users and WooCommerce customers, this bar is clutter that breaks the site layout. Remove it for everyone except admins and editors.

This uses current_user_can() to check capabilities rather than checking role names directly. Capability checks are more reliable when custom roles or role modifications are in play.


6. Custom Dashboard Widget

The WordPress dashboard is cluttered with default widgets most sites do not need. Add a custom widget showing useful site-specific information - recent orders, support links, documentation shortcuts - and optionally remove irrelevant default widgets.

This is useful for client sites. Add links to their documentation, support email, and any custom admin pages in the widget content. Remove the default widgets that clients will never use (Welcome panel, WordPress Events, Quick Draft).


7. Disable REST API User Enumeration

The WordPress REST API exposes usernames at /wp-json/wp/v2/users by default. This is useful for headless setups but a security issue for standard sites - it lets anyone enumerate valid usernames to target with brute force attacks. Disable public access to the users endpoint while keeping the REST API functional for authenticated requests.

This returns a WP_Error for unauthenticated requests to the users endpoint only. All other REST endpoints remain accessible. Authenticated requests (with a valid nonce or application password) still work, so Gutenberg editor functionality is unaffected.


8. Custom WordPress Cron Interval

WordPress has built-in cron schedules: hourly, twicedaily, daily. If you need a custom interval - every 15 minutes, every 6 hours - you need to register it. This snippet adds a custom cron interval and schedules a recurring event to run a function.

Remember: WordPress cron is pseudo-cron - it fires when a visitor loads a page. On low-traffic sites, scheduled tasks may run late. Use a real system cron job calling wp-cron.php directly if timing accuracy matters, and disable default WP-Cron by adding define(‘DISABLE_WP_CRON’, true) to wp-config.php.


9. Defer Non-Critical JavaScript

Render-blocking JavaScript slows page loads. This snippet adds the defer attribute to all enqueued scripts except those explicitly excluded (jQuery and scripts marked as render-critical). Deferring scripts tells the browser to load them after the HTML is parsed, improving perceived load time and Core Web Vitals scores.

Test thoroughly after adding. Some scripts that rely on DOM-ready events may break when deferred. Add their handles to the exclusion array as needed. Check both front end and admin with JavaScript console open to catch errors.


10. Limit Login Attempts

WordPress allows unlimited login attempts by default, making brute-force attacks trivial. This snippet tracks failed login attempts per IP address using transients and blocks further attempts after 5 failures, with a 15-minute lockout. No plugin required.

Adjust MAX_ATTEMPTS (default: 5) and LOCKOUT_DURATION (default: 900 seconds / 15 minutes) constants to match your security requirements. For high-value sites, consider adding email notification to admin when lockouts occur.


Using These Snippets Safely

  • Test on staging first: Always test snippets on a staging site before adding to production. A PHP error in functions.php can white-screen your site.
  • Use must-use plugins: For critical site-wide snippets, put them in wp-content/mu-plugins/ as a .php file. Must-use plugins load before regular plugins and cannot be accidentally deactivated.
  • Use a code manager plugin: WPCode (formerly Code Snippets) lets you add PHP snippets through the admin UI with syntax checking and the ability to disable a snippet without FTP access.
  • Document what each snippet does: Add a PHP file header comment explaining what the snippet does, what it affects, and when it was added. Future you will appreciate it.
  • Update when WordPress updates: Some snippets hook into WordPress internals that change across versions. After major WordPress updates, verify snippets still work as expected.


Where to Store WordPress Snippets

Where you store a snippet determines when it loads and what happens if it breaks. Choose the right location based on the snippet’s purpose and criticality.

functions.php

functions.php is the most common location but has a significant downside: it is theme-specific. When you switch themes, all snippets in functions.php disappear. For site-wide functionality that should persist regardless of theme changes, functions.php is the wrong place.

Use functions.php only for snippets that are theme-specific - things like modifying the_content() output to match the theme’s layout, or registering custom menus the theme uses. Anything that should survive a theme switch belongs elsewhere.

Must-Use Plugins (mu-plugins)

The wp-content/mu-plugins directory contains PHP files that WordPress loads automatically on every request, before regular plugins, and they cannot be deactivated through the admin UI. This makes mu-plugins the most reliable location for site-critical snippets.

Create a file like wp-content/mu-plugins/site-config.php and put your most important snippets there. The disable emojis snippet, login attempt limiter, and REST API user endpoint restriction are all good mu-plugins candidates - they should be active on every request with no risk of accidental deactivation.

A Custom Site Plugin

The cleanest approach for a collection of snippets is a custom site plugin. Create a plugin in wp-content/plugins/site-functions/ with a header comment declaring it as a plugin. Group related snippets into separate files (security.php, performance.php, admin.php) and require them from the main plugin file. This gives you:

  • Theme independence - snippets survive any theme change
  • Activation control - you can deactivate via WP admin if needed
  • Version control friendly - easily tracked in git as a standalone plugin
  • Developer clarity - new developers can find site customizations in one place

WPCode Plugin

For sites managed by non-developers or agencies working with clients, WPCode (the successor to Code Snippets) provides a UI for managing PHP, CSS, and JavaScript snippets. Snippets are stored in the database, can be enabled/disabled from the admin, and have built-in syntax highlighting. The free version is sufficient for most use cases.


Snippet Performance Considerations

Most WordPress snippets have negligible performance impact. But a few patterns can slow down your site if applied naively:

  • Hooks that run on every page load: Be careful with init and wp_head hooks. If your snippet does database queries or file system reads on init, those run on every single page request - including AJAX requests, REST API calls, and admin pages. Add conditional checks (is_front_page(), is_admin(), etc.) where appropriate.
  • Auto-linking in ThirstyAffiliates: The auto-link feature scans all post content for keywords on every page load. Enable it selectively or use a caching plugin to minimize the overhead.
  • Defer scripts snippet: The defer snippet runs a string replace on every script tag. On pages with many enqueued scripts, this is fast but worth measuring with a profiling tool if you notice admin slowness.
  • Login attempt limiter: Transient-based rate limiting adds one get_transient() call per authentication attempt. This is negligible overhead - transients with object caching are a single memory lookup.

Profile before optimizing. Query Monitor (free WordPress plugin) shows you exactly which hooks fire, how long they take, and what database queries they trigger. Enable it on staging after adding new snippets to verify there is no unexpected overhead.

The best WordPress snippet is one that solves a specific problem without adding complexity. If you find yourself writing more than 50 lines for a snippets.php entry, it probably should be a plugin.

Organizing a Growing Snippet Library

As your snippet collection grows beyond 10-15 items, organization becomes important. Random additions to functions.php create technical debt that is slow to untangle later. A structured approach from the start saves time when you need to find, update, or remove a specific snippet.

File-Based Organization in a Site Plugin

Create a dedicated site plugin at wp-content/plugins/site-functions/ with a directory structure that groups related snippets:

  • inc/performance.php - Emoji removal, script deferring, lazy load tweaks
  • inc/security.php - Login attempt limits, REST API restrictions, login URL change
  • inc/admin.php - Dashboard widgets, admin bar control, menu cleanup
  • inc/users.php - Login redirects, role-based capabilities
  • inc/content.php - Excerpt customization, read more links, content filters
  • inc/cron.php - Custom intervals and scheduled tasks

The main plugin file (site-functions.php) requires each file: require_once plugin_dir_path(__FILE__) . ‘inc/performance.php’. This keeps each category of snippet isolated, makes code review cleaner, and lets you disable a category of snippets by commenting out one line.

Naming Conventions

Prefix all your function names and constants with a site-specific prefix to avoid conflicts with plugins and WordPress core. The snippets in this guide use attowp_ as the prefix. For a client site called “Meridian Coffee”, use meridian_ or meri_ as the prefix. Avoid generic prefixes like my_ or site_ that create conflicts when combining code from multiple sources.


When a Snippet Should Become a Plugin

The boundary between “snippet” and “plugin” is fuzzy but there are clear signals that a piece of functionality has outgrown its snippets.php home:

  • It has settings: If the snippet needs configurable options stored in the database, it needs an options page - which means it is a plugin.
  • It has multiple files: JavaScript assets, CSS files, template partials, or includes that a snippet depends on should all be in a self-contained plugin directory.
  • Other sites would benefit from it: If you find yourself copying the snippet to multiple client sites, package it as a small private plugin that can be installed and updated across all sites.
  • It is more than 100 lines: Long snippets are hard to find and maintain. A plugin with a proper file structure is easier to work with.
  • It interacts with third-party APIs: API keys, webhooks, response handling, and error logging benefit from the structure of a plugin with proper settings handling.

The snippets in this guide are all small, self-contained, and suitable for staying as snippets indefinitely. Use them as a baseline and as starting points for more complex custom functionality when your site’s needs grow. Start with building full WordPress plugins when functionality exceeds what a snippet can cleanly handle.


Version Control for Your Snippet Library

Snippets that live in a site plugin can be version-controlled in Git alongside the rest of the site’s custom code. This gives you a history of every change, the ability to revert a snippet that broke something, and the ability to review snippet changes in pull requests.

A minimal git workflow for a site plugin: create a private repository at GitHub or GitLab, clone it as the site plugin directory, commit after every meaningful change. Add a commit message that identifies which snippet changed and why: “security: increase login attempt lockout to 30 min for client requirement”.

For managed WordPress hosting platforms like Kinsta or WP Engine, their Git push-to-deploy features can automatically deploy snippet changes to production after they are merged to the main branch. No FTP needed, no manual deployment - a snippet fix merged and pushed is live within minutes.

Keep Building Better WordPress Sites

These snippets are starter pieces. For more advanced WordPress development techniques, check out the plugin development guides covering custom post types, REST API endpoints, Gutenberg blocks, and plugin architecture patterns. Also see the guide on full WordPress performance optimization WordPress performance optimization for additional server-side and front-end improvements.

All WordPress Developer Guides
Varun Dubey

Written by

Varun Dubey

Varun Dubey runs Wbcom Designs, the WordPress studio he founded in India in 2009. He has spent sixteen years building on WordPress and BuddyPress, shipping client work and products such as Reign, BuddyX, Jetonomy and MediaVerse, and has been putting Claude and OpenAI workflows into production since 2023. He writes up what the studio learns along the way.

More about Varun

No comments yet