WPDev.one

Snippet Library

Copy-pasteable solutions for common WordPress engineering problems. Verified for WP 6.4+.

Showing 105 Snippets

Sort by:
PHP
WP 5.9+
Gutenberg

Register Custom Block Style

Add a "Fancy Border" style to the core Image block. This uses the modern server-side registration method, which only loads the CSS when the style is actually used on a page.

register_block_style('core/image', array(
JS
Gutenberg 14+
Gutenberg

Register Custom Block Variation

Extends the core Group block to create a pre-configured "Hero Section" available directly in the inserter.

wp.blocks.registerBlockVariation('core/group', {
PHP
WP 5.8+
Gutenberg

Add Custom Block Supports

Enable missing design tools (like Line Height, Border, or Spacing) on Core blocks without modifying the block's source code.

add_filter('register_block_type_args', function($args, $name) {
PHP
WP 5.0+
Gutenberg

Disable Gutenberg for Specific Post Types

Conditionally disable the Block Editor and revert to the Classic Editor (or raw HTML) using the use_block_editor_for_post_type filter.

add_filter('use_block_editor_for_post_type', function($use_block_editor, $post_type) {
JS
Gutenberg 12.0+
Gutenberg

Customize Block Inserter Categories

Remove clutter by unregistering specific blocks or categories from the "Plus" menu. This prevents clients from inserting complex blocks like "Verse" or "Archives" that break your design system.

wp.hooks.addFilter('blocks.registerBlockType', 'my-theme/filter-blocks', function(settings, name) {
SQL
Dangerous
Performance

Clean Orphaned Post Meta

A direct SQL query to identify and remove row entries in wp_postmeta that are linked to post IDs that no longer exist in wp_posts.

DELETE pm FROM wp_postmeta pm
CLI
WP-CLI 2.0+
Performance

Regenerate Thumbnails via SSH

Efficiently regenerate WordPress image thumbnails via WP-CLI to avoid PHP timeouts and memory errors. Ideal for large media libraries.

wp media regenerate --yes
PHP
WP 5.0+
Gutenberg

Dynamic Block Render Callback

Create a server-side render callback for dynamic blocks that fetches data on each page load.

register_block_type('my-plugin/dynamic-block', array(
PHP
WP 5.0+
Gutenberg

Conditional Block Rendering

Conditionally render block content based on user roles, post meta, or custom conditions.

add_filter('render_block', function($block_content, $block) {
PHP
WP 5.9+
Gutenberg

Server-Side Inner Blocks

Process and render inner blocks on the server side for better performance and SEO.

function render_inner_blocks($block) {
JS
Gutenberg 10.0+
Gutenberg

Block Context Provider

Create a custom block context provider to share data between parent and child blocks.

const { registerBlockType } = wp.blocks;
JS
Gutenberg 5.0+
Gutenberg

Block Deprecation Handler

Handle deprecated block versions and migrate old block attributes to new format.

const deprecated = [{
PHP
WP 5.5+
Gutenberg

Block Pattern Category

Register a custom block pattern category for organizing reusable block patterns.

register_block_pattern_category('my-category', array(
PHP
WP 5.0+
Gutenberg

Register Private Block

Register a block that is only available internally and not shown in the block inserter.

register_block_type('my-plugin/private-block', array(
PHP
WP 5.5+
Gutenberg

Remove Core Patterns

Remove default WordPress block patterns from the pattern inserter to simplify the editor.

remove_theme_support('core-block-patterns');
PHP
WP 5.9+
Gutenberg

Lock Block Template

Lock specific blocks or entire templates to prevent client modifications.

add_filter('block_editor_settings_all', function($settings) {
JS
Gutenberg 6.0+
Gutenberg

Restrict Blocks by Role

Limit which blocks are available in the inserter based on user roles.

wp.hooks.addFilter('blocks.registerBlockType', 'my-theme/restrict-blocks', function(settings, name) {
JS
Gutenberg 5.0+
Gutenberg

Auto Insert Block on Load

Automatically insert a specific block when the editor loads for new posts.

wp.data.dispatch('core/editor').insertBlocks([
JS
Gutenberg 6.0+
Gutenberg

Hide Block Settings Panel

Hide the block settings sidebar panel for specific blocks or user roles.

wp.plugins.registerPlugin('hide-settings-panel', {
JS
Gutenberg 5.0+
Gutenberg

Add Editor Notice Banner

Display a custom notice banner in the block editor to inform users about important information.

const { createElement } = wp.element;
JS
Gutenberg 5.0+
Gutenberg

Custom Sidebar Plugin

Create a custom sidebar plugin for the block editor with custom controls and settings.

const { registerPlugin } = wp.plugins;
JS
Gutenberg 5.0+
Gutenberg

Inspector Controls Hook

Add custom inspector controls to blocks using the Block Inspector Controls API.

const { InspectorControls } = wp.blockEditor;
JS
Gutenberg 5.0+
Gutenberg

Reusable Media Picker

Create a reusable media picker component for selecting images, videos, or other media.

const { MediaUpload } = wp.blockEditor;
JS
Gutenberg 5.0+
Gutenberg

Debounced Text Control

Create a text input control with debounced onChange handler for better performance.

const { useState, useEffect } = wp.element;
JS
Gutenberg 5.0+
Gutenberg

Block Toolbar Extension

Add custom toolbar buttons to blocks for additional functionality.

const { BlockControls } = wp.blockEditor;
JS
Gutenberg 5.0+
Gutenberg

Custom Block Store

Create a custom Redux store for managing block-specific state and data.

const { registerStore } = wp.data;
JS
Gutenberg 5.0+
Gutenberg

WP Data Cache Layer

Implement a caching layer for wp.data to improve performance and reduce API calls.

const { select, dispatch } = wp.data;
JS
Gutenberg 5.0+
Gutenberg

Async Block Data Fetch

Fetch data asynchronously in blocks using the WordPress REST API with loading states.

const { apiFetch } = wp;
PHP
WP 2.5+
Admin

Add Custom Columns to Admin

Add custom columns to the WordPress admin post list table to display custom meta or data.

add_filter('manage_posts_columns', function($columns) {
PHP
WP 2.5+
Admin

Make Columns Sortable

Make custom admin columns sortable by clicking the column header.

add_filter('manage_edit-post_sortable_columns', function($columns) {
PHP
WP 2.5+
Admin

Render Column with Meta

Display custom post meta or computed values in admin list table columns.

add_action('manage_posts_custom_column', function($column, $post_id) {
PHP
WP 2.7+
Admin

Bulk Edit Custom Column

Enable bulk editing for custom columns in the WordPress admin.

add_action('bulk_edit_custom_box', function($column_name, $post_type) {
PHP
WP 2.5+
Admin

Remove Dashboard Widgets

Remove default WordPress dashboard widgets to create a cleaner admin experience.

add_action('wp_dashboard_setup', function() {
PHP
WP 2.5+
Admin

Custom Admin Footer

Replace the default WordPress admin footer text with custom branding or information.

add_filter('admin_footer_text', function() {
PHP
WP 2.5+
Admin

Add Admin Menu Separator

Add visual separators between admin menu items for better organization.

add_action('admin_menu', function() {
PHP
WP 2.5+
Admin

Sticky Admin Notices

Create persistent admin notices that remain visible until dismissed by the user.

add_action('admin_notices', function() {
JS
WP 5.0+
Admin

Admin Dark Mode Toggle

Add a dark mode toggle button to the WordPress admin interface.

const toggleDarkMode = () => {
PHP
WP 3.3+
Admin

Contextual Help Tabs

Add custom help tabs to admin pages to provide context-specific documentation.

add_action('admin_head', function() {
PHP
WP 2.5+
Admin

Custom Login Logo

Replace the default WordPress logo on the login page with your custom branding.

add_action('login_enqueue_scripts', function() {
PHP
WP 2.5+
Admin

Disable Login Shake

Remove the shake animation effect when login credentials are incorrect.

add_action('login_head', function() {
PHP
WP 4.0+
Admin

Magic Login Link

Generate secure one-time login links that expire after use or time limit.

function generate_magic_login_link($user_id) {
PHP
WP 2.5+
Admin

Limit Login Attempts

Prevent brute force attacks by limiting the number of failed login attempts.

add_filter('authenticate', function($user, $username, $password) {
PHP
WP 2.5+
Admin

Role-Based Login Redirect

Redirect users to different pages after login based on their user role.

add_filter('login_redirect', function($redirect_to, $requested_redirect_to, $user) {
PHP
WP 2.0+
Admin

Clone User Role

Duplicate an existing user role with all its capabilities for customization.

function clone_user_role($source_role, $new_role, $display_name) {
PHP
WP 2.0+
Admin

Temporary Capabilities

Grant temporary capabilities to users that expire after a set time period.

add_filter('user_has_cap', function($allcaps, $cap, $args) {
PHP
WP 3.1+
Admin

Admin Impersonation

Allow administrators to temporarily log in as another user for support purposes.

add_action('admin_bar_menu', function($wp_admin_bar) {
SQL
All Versions
Performance

Delete Transients

Clean up expired and orphaned transients from the WordPress options table.

DELETE FROM wp_options WHERE option_name LIKE '_transient_%'
SQL
All Versions
Performance

Find Unused Tags

Identify tags that are not assigned to any posts for cleanup.

SELECT t.term_id, t.name FROM wp_terms t
SQL
All Versions
Performance

Optimize Autoloaded Options

Identify and optimize options that are unnecessarily autoloaded on every page request.

SELECT option_name, LENGTH(option_value) as size FROM wp_options
SQL
All Versions
Performance

Find Large Postmeta

Identify postmeta entries that are unusually large and may be causing performance issues.

SELECT meta_id, post_id, meta_key, LENGTH(meta_value) as size FROM wp_postmeta
PHP
WP 3.1+
Performance

Pre Get Posts Optimizations

Optimize WordPress queries using the pre_get_posts hook to reduce database load.

add_action('pre_get_posts', function($query) {
PHP
WP 2.1+
Performance

Disable Paging SQL_CALC

Remove SQL_CALC_FOUND_ROWS from paginated queries to improve performance.

add_filter('found_posts_query', function($sql) {
PHP
WP 3.0+
Performance

Query Monitor Helpers

Add custom query monitoring and debugging helpers for development.

add_filter('log_query_custom_data', function($data, $query) {
CLI
WP-CLI 1.0+
Performance

Search Replace Database

Safely search and replace URLs or strings in the WordPress database using WP-CLI.

wp search-replace 'old-url.com' 'new-url.com'
CLI
WP-CLI 1.0+
Performance

Create Admin User

Create a new WordPress administrator user via WP-CLI command line.

wp user create admin admin@example.com --role=administrator
CLI
WP-CLI 1.0+
Performance

Bulk Post Generator

Generate multiple posts programmatically using WP-CLI for testing or content migration.

wp post generate --count=100 --post_type=post
CLI
WP-CLI 1.0+
Performance

Cron Health Check

Monitor and debug WordPress cron jobs to ensure scheduled tasks are running correctly.

wp cron event list
PHP
WP 3.6+
Performance

Disable Heartbeat API

Disable the WordPress Heartbeat API to reduce server load and improve performance.

add_action('init', function() {
PHP
WP 2.0+
Performance

Fragment Caching

Implement fragment caching for expensive operations like complex queries or API calls.

function get_cached_fragment($key, $callback, $expiration = 3600) {
PHP
WP 2.0+
Performance

Object Cache Warming

Pre-populate the object cache with frequently accessed data to improve response times.

function warm_object_cache() {
PHP
WP 2.0+
Performance

HTTP Cache Headers

Set proper HTTP cache headers for static assets and API responses.

add_action('send_headers', function() {
PHP
WP 2.5+
Media

Upload SVG Safely

Enable SVG uploads in WordPress with security sanitization to prevent XSS attacks.

add_filter('upload_mimes', function($mimes) {
JS
Modern Browsers
Media

Lazy Load Background Images

Implement lazy loading for CSS background images to improve page load performance.

const lazyBackgroundObserver = new IntersectionObserver((entries) => {
PHP
WP 2.5+
Media

Generate WebP on Upload

Automatically generate WebP versions of uploaded images for better performance.

add_filter('wp_handle_upload_prefilter', function($file) {
JS
WP 3.5+
Media

Media Library Filters

Add custom filters to the WordPress media library for better organization.

wp.media.controller.Library.extend({
PHP
WP 2.5+
Media

Auto Alt Text Generator

Automatically generate alt text for images using AI or image analysis.

add_action('add_attachment', function($post_id) {
PHP
WP 3.5+
Security

Disable XML-RPC

Disable XML-RPC to prevent brute force attacks and improve security.

add_filter('xmlrpc_enabled', '__return_false');
PHP
WP 4.7+
Security

REST API Rate Limiting

Implement rate limiting for the WordPress REST API to prevent abuse.

add_filter('rest_authentication_errors', function($result) {
PHP
WP 2.0+
Security

Hide WP Version

Remove WordPress version information from the frontend to improve security.

remove_action('wp_head', 'wp_generator');
PHP
WP 2.0+
Security

Nonce Validation Wrapper

Create a reusable wrapper function for nonce validation in forms and AJAX requests.

function validate_nonce($action, $nonce) {
PHP
WP 2.5+
Security

Admin Action Logger

Log all admin actions for security auditing and debugging purposes.

add_action('admin_init', function() {
PHP
WP 2.0+
Security

Bot Detection Honeypot

Implement a honeypot field in forms to detect and block bot submissions.

add_action('comment_form', function() {
PHP
WooCommerce 3.0+
WooCommerce

Remove Checkout Fields

Remove unnecessary fields from the WooCommerce checkout form.

add_filter('woocommerce_checkout_fields', function($fields) {
PHP
WooCommerce 3.0+
WooCommerce

Add Custom Checkout Field

Add custom fields to the WooCommerce checkout form for additional information.

add_action('woocommerce_after_order_notes', function($checkout) {
PHP
WooCommerce 3.0+
WooCommerce

Conditional Payment Gateway

Show or hide payment gateways based on cart total, product categories, or other conditions.

add_filter('woocommerce_available_payment_gateways', function($gateways) {
PHP
WooCommerce 3.0+
WooCommerce

Checkout Field Validation

Add custom validation rules to WooCommerce checkout fields.

add_action('woocommerce_checkout_process', function() {
PHP
WooCommerce 3.0+
WooCommerce

Change Add to Cart Text

Customize the "Add to Cart" button text for different product types or conditions.

add_filter('woocommerce_product_add_to_cart_text', function($text, $product) {
PHP
WooCommerce 3.0+
WooCommerce

Hide Price If Logged Out

Hide product prices for logged-out users to encourage registration.

add_filter('woocommerce_get_price_html', function($price, $product) {
PHP
WooCommerce 3.0+
WooCommerce

Product Badges Dynamic

Display dynamic product badges based on stock status, sale status, or custom conditions.

add_action('woocommerce_before_shop_loop_item_title', function() {
PHP
WooCommerce 3.0+
WooCommerce

Stock Progress Bar

Display a visual progress bar showing remaining stock quantity for products.

add_action('woocommerce_single_product_summary', function() {
JS
WooCommerce 3.0+
WooCommerce

Variation Preselection

Automatically preselect product variations based on URL parameters or user preferences.

jQuery(document).ready(function($) {
PHP
WooCommerce 3.0+
WooCommerce

Custom Order Status

Register custom order statuses for WooCommerce orders to match your workflow.

add_action('init', function() {
PHP
WooCommerce 3.0+
WooCommerce

Auto Complete Virtual Orders

Automatically mark virtual product orders as completed upon payment.

add_action('woocommerce_thankyou', function($order_id) {
PHP
WooCommerce 3.0+
WooCommerce

Order Meta Sync

Synchronize order meta data with external systems or update related records.

add_action('woocommerce_checkout_update_order_meta', function($order_id) {
PHP
WP 4.7+
API

Modify REST Response

Customize the data returned by WordPress REST API endpoints.

add_filter('rest_prepare_post', function($response, $post) {
PHP
WP 4.7+
API

Auth Middleware

Create custom authentication middleware for REST API endpoints.

add_filter('rest_authentication_errors', function($result) {
PHP
WP 4.7+
API

Pagination Helpers

Add pagination metadata and helpers to REST API responses.

function add_pagination_to_response($response, $request) {
PHP
WP 4.7+
API

Response Schema Validation

Validate REST API response data against a defined schema.

function validate_response_schema($data, $schema) {
PHP
WP 4.7+
API

JWT Auth Implementation

Implement JSON Web Token authentication for WordPress REST API.

add_filter('determine_current_user', function($user_id) {
PHP
WP 4.7+
API

CORS Headers Setup

Configure CORS headers for cross-origin REST API requests.

add_action('rest_api_init', function() {
PHP
WP 4.7+
API

API Key Auth Layer

Implement API key authentication for REST API endpoints.

add_filter('rest_authentication_errors', function($result) {
PHP
WP 4.7+
API

Webhook Receiver

Create an endpoint to receive and process webhooks from external services.

add_action('rest_api_init', function() {
PHP
WP 4.7+
API

Retry Failed Webhooks

Implement automatic retry logic for failed webhook deliveries.

function retry_webhook($webhook_id, $max_retries = 3) {
PHP
WP 4.7+
API

Signed Payload Validation

Validate webhook payloads using cryptographic signatures for security.

function validate_webhook_signature($payload, $signature, $secret) {
Code
Modern Browsers
Theme Engine

CSS Variables Setup

Configure CSS custom properties (variables) for dynamic theming and design tokens.

:root {
PHP
WP 5.8+
Theme Engine

Typography Scale Generator

Generate a consistent typography scale using PHP for theme.json or CSS.

function generate_typography_scale($base_size = 16, $ratio = 1.25) {
JS
Modern Browsers
Theme Engine

Dark Mode System

Implement a complete dark mode system with user preference detection and toggle.

const darkMode = {
JS
WP 5.8+
Theme Engine

Tailwind Config Sync

Sync Tailwind CSS configuration with WordPress theme.json settings.

module.exports = {
PHP
WP 5.0+
Theme Engine

Component Registry

Create a centralized component registry system for reusable theme components.

class Component_Registry {
PHP
WP 2.1+
Automation

Scheduled Content Publishing

Implement advanced scheduled publishing with custom conditions and notifications.

add_action('wp_scheduled_delete', function() {
PHP
WP 2.0+
Automation

Auto Internal Linking

Automatically create internal links between related posts based on keywords or tags.

add_filter('the_content', function($content) {
PHP
WP 2.0+
Automation

AI Content Hooks

Integrate AI services to automatically generate or enhance content.

add_action('save_post', function($post_id) {
PHP
WP 2.0+
Automation

Form to Post Pipeline

Automatically convert form submissions into WordPress posts or custom post types.

add_action('gform_after_submission', function($entry, $form) {
PHP
WP 2.0+
Automation

Activity-Based Email Trigger

Send automated emails based on user activity, post updates, or custom events.

add_action('wp_insert_post', function($post_id, $post) {
PHP
WP 4.7+
API

Register Custom REST API Endpoint

Create a tailored API route (e.g., /wp-json/my-site/v1/latest) to fetch specific data efficiently, reducing payload size for Headless or JS-heavy sites.

add_action('rest_api_init', function() {