WordPress Snippet Library

Searchable WordPress snippets for security, performance, customization, admin, SEO, and debugging workflows.

WordPressPopularSnippets: 24

24 snippets found

Disable XML-RPC

Block all XML-RPC requests to reduce brute-force and pingback abuse.

Security
add_filter( 'xmlrpc_enabled', '__return_false' );
1 line

Hide Login Error Messages

Avoid leaking whether the username or password was incorrect.

Security
add_filter( 'login_errors', function() {
    return 'Login failed. Please check your credentials.';
} );
3 lines

Disable File Editing in Admin

Prevent plugin and theme code editing inside the dashboard.

Security
// Add to wp-config.php
define( 'DISALLOW_FILE_EDIT', true );
2 lines

Force SSL for Admin

Require HTTPS for wp-admin and the login screen.

Security
// Add to wp-config.php
define( 'FORCE_SSL_ADMIN', true );
define( 'FORCE_SSL_LOGIN', true );
3 lines

Disable REST API for Guests

Restrict REST API access to authenticated users only.

Security
add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) return $result;
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            'REST API restricted to authenticated users.',
            [ 'status' => 401 ]
        );
    }
    return $result;
} );
11 lines

Disable Emoji Script

Remove emoji scripts and styles to reduce frontend payload.

Performance
add_action( 'init', function() {
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );
} );
5 lines

Remove jQuery Migrate

Keep frontend jQuery leaner for modern themes.

Performance
add_action( 'wp_default_scripts', function( $scripts ) {
    if ( ! is_admin() && isset( $scripts->registered['jquery'] ) ) {
        $deps = $scripts->registered['jquery']->deps;
        $scripts->registered['jquery']->deps = array_diff( $deps, [ 'jquery-migrate' ] );
    }
} );
6 lines

Defer Non-Critical Scripts

Attach defer to safe frontend script handles.

Performance
add_filter( 'script_loader_tag', function( $tag, $handle ) {
    $exclude = [ 'jquery', 'jquery-core', 'wp-embed' ];
    if ( in_array( $handle, $exclude, true ) ) {
        return $tag;
    }
    return str_replace( ' src=', ' defer src=', $tag );
}, 10, 2 );
7 lines

Limit Stored Revisions

Control revision growth and tune autosave intervals.

Performance
// Add to wp-config.php
define( 'WP_POST_REVISIONS', 5 );
define( 'AUTOSAVE_INTERVAL', 300 );
3 lines

Throttle Heartbeat API

Reduce Heartbeat API chatter for less admin noise.

Performance
add_filter( 'heartbeat_settings', function( $settings ) {
    $settings['interval'] = 120;
    return $settings;
} );
4 lines

Register Custom Post Type

Create a complete project-style custom post type starter.

Customization
add_action( 'init', function() {
    register_post_type( 'project', [
        'labels' => [
            'name'          => 'Projects',
            'singular_name' => 'Project',
        ],
        'public'       => true,
        'has_archive'  => true,
        'menu_icon'    => 'dashicons-portfolio',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'excerpt' ],
        'show_in_rest' => true,
        'rewrite'      => [ 'slug' => 'projects', 'with_front' => false ],
    ] );
} );
14 lines

Register Custom Taxonomy

Attach a hierarchical taxonomy to a custom post type.

Customization
add_action( 'init', function() {
    register_taxonomy( 'project_type', [ 'project' ], [
        'hierarchical' => true,
        'public'       => true,
        'show_in_rest' => true,
        'rewrite'      => [ 'slug' => 'project-type' ],
    ] );
} );
8 lines

Register Custom Image Sizes

Add custom image crops for hero banners and cards.

Customization
add_action( 'after_setup_theme', function() {
    add_image_size( 'hero-banner', 1600, 600, true );
    add_image_size( 'card-thumb', 480, 320, true );
    add_image_size( 'square-thumb', 400, 400, true );
} );
5 lines

Register Widget Area

Create a reusable sidebar or footer widget area.

Customization
add_action( 'widgets_init', function() {
    register_sidebar( [
        'name'          => 'Primary Sidebar',
        'id'            => 'sidebar-primary',
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ] );
} );
10 lines

Enqueue Theme Assets Properly

Load CSS and JS with versioning plus localized data.

Customization
add_action( 'wp_enqueue_scripts', function() {
    wp_enqueue_style( 'my-theme', get_stylesheet_directory_uri() . '/assets/css/main.css', [], wp_get_theme()->get( 'Version' ) );
    wp_enqueue_script( 'my-theme-js', get_stylesheet_directory_uri() . '/assets/js/app.js', [ 'jquery' ], wp_get_theme()->get( 'Version' ), true );
    wp_localize_script( 'my-theme-js', 'myData', [
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'my_nonce' ),
    ] );
} );
8 lines

Add Dashboard Widget

Place a simple stats or info card on the dashboard home.

Admin
add_action( 'wp_dashboard_setup', function() {
    wp_add_dashboard_widget( 'my_stats_widget', 'Site Statistics', function() {
        echo '<p>Published posts: ' . wp_count_posts()->publish . '</p>';
        echo '<p>Total users: ' . count_users()['total_users'] . '</p>';
    } );
} );
6 lines

Hide Admin Bar for Subscribers

Keep the frontend cleaner for low-permission users.

Admin
add_action( 'after_setup_theme', function() {
    if ( ! current_user_can( 'edit_posts' ) ) {
        show_admin_bar( false );
    }
} );
5 lines

Customize Admin Footer Text

Replace the default WordPress footer text inside wp-admin.

Admin
add_filter( 'admin_footer_text', function() {
    return 'Built with care by GAP3.';
} );
3 lines

Output JSON-LD Website Schema

Add a simple Website schema object with search action support.

SEO
add_action( 'wp_head', function() {
    $schema = [
        '@context' => 'https://schema.org',
        '@type'    => 'WebSite',
        'name'     => get_bloginfo( 'name' ),
        'url'      => home_url( '/' ),
        'potentialAction' => [
            '@type'       => 'SearchAction',
            'target'      => home_url( '/?s={search_term_string}' ),
            'query-input' => 'required name=search_term_string',
        ],
    ];
    echo '<script type="application/ld+json">' . wp_json_encode( $schema ) . '</script>';
} );
14 lines

Fallback Meta Description

Generate a meta description from excerpt or content automatically.

SEO
add_action( 'wp_head', function() {
    if ( ! is_singular() ) return;
    global $post;
    $excerpt = $post->post_excerpt ? $post->post_excerpt : wp_trim_words( wp_strip_all_tags( $post->post_content ), 30 );
    if ( $excerpt ) {
        echo '<meta name="description" content="' . esc_attr( $excerpt ) . '" />';
    }
} );
8 lines

Customize Title Separator

Switch the document title separator to better fit your brand.

SEO
add_filter( 'document_title_separator', function() {
    return '|';
} );
3 lines

Enable Full WP Debug Mode

Switch on core debugging flags during development.

Debugging
// Add to wp-config.php
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'SCRIPT_DEBUG', true );
define( 'SAVEQUERIES', true );
6 lines

Custom Debug Logger

Write readable arrays or strings into debug.log.

Debugging
function wpdebug( $data, $label = '' ) {
    if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) return;
    $prefix = $label ? '[' . $label . '] ' : '';
    $output = is_array( $data ) || is_object( $data ) ? print_r( $data, true ) : (string) $data;
    error_log( '[WP Debug] ' . $prefix . $output );
}
6 lines

Show Query Count in Footer

Display query count, load time, and memory usage for admins.

Debugging
add_action( 'wp_footer', function() {
    if ( ! current_user_can( 'administrator' ) ) return;
    $queries = get_num_queries();
    $time = timer_stop( 0, 3 );
    $memory = round( memory_get_peak_usage( true ) / 1048576, 2 ) . 'MB';
    echo '<!-- Q:' . $queries . ' T:' . $time . 's M:' . $memory . ' -->';
} );
7 lines

Validate in Staging

Test snippets on staging first. Many hooks are safe individually, but combinations can change admin or frontend behavior quickly.

Prefer a Utility Plugin

Keep custom snippets inside a small utility plugin when possible instead of stacking everything into functions.php.

Adjust Before Pasting

Review sanitization, capabilities, and conditionals before copying snippets into live client sites.

Technologies

Our Tech Stack

FigmaFigma
React.jsReact.js
Next.jsNext.js
TypeScriptTypeScript
ShopifyShopify
WordPressWordPress
HTML5HTML5
CSS3CSS3
TailwindTailwind
FramerFramer
FigmaFigma
React.jsReact.js
Next.jsNext.js
TypeScriptTypeScript
ShopifyShopify
WordPressWordPress
HTML5HTML5
CSS3CSS3
TailwindTailwind
FramerFramer
FigmaFigma
React.jsReact.js
Next.jsNext.js
TypeScriptTypeScript
ShopifyShopify
WordPressWordPress
HTML5HTML5
CSS3CSS3
TailwindTailwind
FramerFramer
PHPPHP
GitGit
MySQLMySQL
AWS/VercelAWS/Vercel
IllustratorIllustrator
PhotoshopPhotoshop
SassSass
Node.jsNode.js
StripeStripe
GraphQLGraphQL
PHPPHP
GitGit
MySQLMySQL
AWS/VercelAWS/Vercel
IllustratorIllustrator
PhotoshopPhotoshop
SassSass
Node.jsNode.js
StripeStripe
GraphQLGraphQL
PHPPHP
GitGit
MySQLMySQL
AWS/VercelAWS/Vercel
IllustratorIllustrator
PhotoshopPhotoshop
SassSass
Node.jsNode.js
StripeStripe
GraphQLGraphQL