SNIPPET LIBRARY

A collection of practical WordPress code snippets.

From small tweaks to useful customizations, this library is meant to help solve common problems and make everyday WordPress work a little easier. Snippets are organized by topic and can be searched and filtered to quickly find what you need.

Snippets are provided as-is. Always review and test code changes before using them on a live site.

Browse by topic or search for a specific snippet.
Disable WooCommerce Scripts on Non-WooCommerce Pages

Prevents WooCommerce assets from loading on pages that don’t use them.

add_action( 'wp_enqueue_scripts', 'smw_dequeue_woocommerce_assets', 99 );
function smw_dequeue_woocommerce_assets() {
	if ( function_exists( 'is_woocommerce' ) && ( is_woocommerce() || is_cart() || is_checkout() || is_account_page() ) ) {
		return;
	}

	// Styles
	wp_dequeue_style( 'woocommerce-general' );
	wp_dequeue_style( 'woocommerce-layout' );
	wp_dequeue_style( 'woocommerce-smallscreen' );

	// Scripts (common handles)
	wp_dequeue_script( 'wc-add-to-cart' );
	wp_dequeue_script( 'woocommerce' );
	wp_dequeue_script( 'js-cookie' );
}
0 / 0
Disable Embeds

Disables oEmbed to reduce extra requests and script weight.

add_action( 'init', 'smw_disable_embeds' );
function smw_disable_embeds() {
	remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
	remove_action( 'wp_head', 'wp_oembed_add_host_js' );
}
0 / 0
Lazy Load Iframes

Adds loading=”lazy” to iframes in content where missing.

add_filter( 'the_content', 'smw_lazy_load_iframes', 20 );
function smw_lazy_load_iframes( $content ) {
	if ( false === strpos( $content, '<iframe' ) ) return $content;

	return preg_replace(
		'/(<iframe(?![^>]*loading=)[^>]*)(>)/i',
		'$1 loading="lazy"$2',
		$content
	);
}
0 / 0
Limit Heartbeat on Front-End

Reduces WordPress Heartbeat frequency on the front-end.

add_filter( 'heartbeat_settings', 'smw_heartbeat_settings' );
function smw_heartbeat_settings( $settings ) {
	if ( ! is_admin() ) {
		$settings['interval'] = 60; // seconds
	}
	return $settings;
}
0 / 0
Disable RSS Feeds

Disables RSS/Atom feeds by redirecting feed URLs to the homepage.

add_action( 'do_feed',      'smw_disable_feeds', 1 );
add_action( 'do_feed_rdf',  'smw_disable_feeds', 1 );
add_action( 'do_feed_rss',  'smw_disable_feeds', 1 );
add_action( 'do_feed_rss2', 'smw_disable_feeds', 1 );
add_action( 'do_feed_atom', 'smw_disable_feeds', 1 );

function smw_disable_feeds() {
	wp_safe_redirect( home_url() );
	exit;
}
0 / 0
Remove Unnecessary Elements from

Cleans up the site’s output by removing unused WordPress links and meta tags.

/**
 * Remove unnecessary default WordPress elements from <head>
 *
 * This helps reduce clutter in the page source and slightly
 * improves performance and privacy.
 */

add_action( 'init', 'smw_cleanup_wp_head' );
function smw_cleanup_wp_head() {

	// Remove WordPress version
	remove_action( 'wp_head', 'wp_generator' );

	// Remove Windows Live Writer manifest
	remove_action( 'wp_head', 'wlwmanifest_link' );

	// Remove RSD (Really Simple Discovery) link
	remove_action( 'wp_head', 'rsd_link' );

	// Remove shortlink
	remove_action( 'wp_head', 'wp_shortlink_wp_head' );

	// Remove adjacent post links
	remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );

	// Remove extra feed links
	remove_action( 'wp_head', 'feed_links_extra', 3 );
}
0 / 0
Remove Emoji Scripts

Disables WordPress emoji scripts and styles to reduce extra front-end assets.

/**
 * Disable WordPress emoji scripts/styles
 *
 * This removes the extra emoji JS/CSS WordPress loads by default.
 * Removing this snippet restores emoji support.
 */

add_action( 'init', 'smw_disable_emojis' );
function smw_disable_emojis() {

	// Front-end + admin scripts/styles
	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
	remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );

	remove_action( 'wp_print_styles', 'print_emoji_styles' );
	remove_action( 'admin_print_styles', 'print_emoji_styles' );

	// Feeds + emails
	remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
	remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
	remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );

	// TinyMCE
	add_filter( 'tiny_mce_plugins', 'smw_disable_emojis_tinymce' );

	// Remove emoji CDN from DNS prefetch
	add_filter( 'wp_resource_hints', 'smw_disable_emojis_remove_dns_prefetch', 10, 2 );
}

function smw_disable_emojis_tinymce( $plugins ) {
	if ( is_array( $plugins ) ) {
		return array_diff( $plugins, array( 'wpemoji' ) );
	}
	return array();
}

function smw_disable_emojis_remove_dns_prefetch( $urls, $relation_type ) {
	if ( 'dns-prefetch' === $relation_type ) {
		$emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );
		$urls = array_diff( $urls, array( $emoji_svg_url ) );
	}
	return $urls;
}
0 / 0
Disable File Editing in WP Admin

Disables the built-in theme/plugin editor in wp-admin.

define( 'DISALLOW_FILE_EDIT', true );
0 / 0
Require Strong Passwords for Admins

Enforces a minimum password length for administrators on profile updates.

add_action( 'user_profile_update_errors', 'smw_admin_password_min_length', 10, 3 );
function smw_admin_password_min_length( $errors, $update, $user ) {
	if ( ! user_can( $user, 'administrator' ) ) return;

	if ( isset( $_POST['pass1'] ) && $_POST['pass1'] !== '' ) {
		if ( strlen( $_POST['pass1'] ) < 12 ) {
			$errors->add( 'password_too_short', 'Admin passwords must be at least 12 characters.' );
		}
	}
}
0 / 0
Force Logout Idle Users (Front-End)

Logs users out after 2 hours of inactivity (front-end heartbeat-free approach).

add_action( 'init', 'smw_idle_logout' );
function smw_idle_logout() {
	if ( ! is_user_logged_in() ) return;

	$timeout = 2 * HOUR_IN_SECONDS;
	$key     = 'smw_last_active_' . get_current_user_id();
	$last    = (int) get_user_meta( get_current_user_id(), $key, true );

	if ( $last && ( time() - $last ) > $timeout ) {
		wp_logout();
		wp_safe_redirect( home_url() );
		exit;
	}

	update_user_meta( get_current_user_id(), $key, time() );
}
0 / 0
Remove Query Strings from Static Assets

Removes ?ver= query strings from scripts/styles (can help some caches).

add_filter( 'script_loader_src', 'smw_remove_asset_versions', 15, 1 );
add_filter( 'style_loader_src',  'smw_remove_asset_versions', 15, 1 );
function smw_remove_asset_versions( $src ) {
	return remove_query_arg( 'ver', $src );
}
0 / 0
Remove WordPress Version Information

Removes the WordPress version number from the site’s source code.

add_filter( 'the_generator', 'smw_remove_wp_version' );
function smw_remove_wp_version() {
	return '';
}
0 / 0
Remove Detailed Login Error Messages

Replaces WordPress login error messages with a generic message.

/**
 * Remove detailed WordPress login error messages
 *
 * This helps prevent attackers from learning whether a username
 * or password was incorrect during a failed login attempt.
 */

add_filter( 'login_errors', 'smw_generic_login_error_message' );
function smw_generic_login_error_message() {
	return 'Oops! Something went wrong. Please try again.';
}
0 / 0
Change “Place Order” Text on WooCommerce Checkout

Updates the text of the checkout submit button on WooCommerce checkout pages.

/**
 * Change the WooCommerce checkout button text
 */
add_filter( 'woocommerce_order_button_text', 'smw_change_checkout_button_text' );

function smw_change_checkout_button_text() {
	return __( 'Submit Registration', 'woocommerce' );
}
0 / 0
Redirect to Checkout After Add to Cart

Sends customers directly to the checkout page after adding a product to the cart.

/**
 * Redirect to checkout after adding a product to the cart
 */
add_filter( 'woocommerce_add_to_cart_redirect', 'smw_redirect_to_checkout_after_add_to_cart' );

function smw_redirect_to_checkout_after_add_to_cart() {
	return wc_get_checkout_url();
}
0 / 0
Skip Cart Page

Redirects users directly to checkout when visiting the cart page.

add_action( 'template_redirect', 'smw_skip_cart' );
function smw_skip_cart() {
	if ( function_exists( 'is_cart' ) && is_cart() ) {
		wp_safe_redirect( wc_get_checkout_url() );
		exit;
	}
}
0 / 0
Empty Cart on Logout

Empties the WooCommerce cart when a user logs out.

add_action( 'wp_logout', 'smw_empty_cart_on_logout' );
function smw_empty_cart_on_logout() {
	if ( function_exists( 'WC' ) && WC()->cart ) {
		WC()->cart->empty_cart();
	}
}
0 / 0
Hide Shipping When Free Shipping Is Available

Hides other shipping methods when free shipping is available.

add_filter( 'woocommerce_package_rates', 'smw_hide_shipping_when_free', 100 );
function smw_hide_shipping_when_free( $rates ) {
	$free = array();
	foreach ( $rates as $rate_id => $rate ) {
		if ( 'free_shipping' === $rate->method_id ) {
			$free[ $rate_id ] = $rate;
			break;
		}
	}
	return ! empty( $free ) ? $free : $rates;
}
0 / 0
Auto Apply Coupon

Automatically applies a coupon code in the cart/checkout.

add_action( 'wp_loaded', 'smw_auto_apply_coupon' );
function smw_auto_apply_coupon() {
	if ( is_admin() && ! wp_doing_ajax() ) return;
	if ( ! function_exists( 'WC' ) || ! WC()->cart ) return;

	$coupon = 'WELCOME';
	if ( ! WC()->cart->has_discount( $coupon ) ) {
		WC()->cart->apply_coupon( $coupon );
	}
}
0 / 0
Rename “Add to Cart” Button (Single Product)

Changes the Add to Cart button text on single product pages.

add_filter( 'woocommerce_product_single_add_to_cart_text', function() {
	return 'Buy Now';
} );

--- Hide Prices for Logged-Out Users ---
Description: Hides product prices unless the user is logged in.

add_filter( 'woocommerce_get_price_html', 'smw_hide_price_logged_out' );
function smw_hide_price_logged_out( $price ) {
	if ( ! is_user_logged_in() ) {
		return '';
	}
	return $price;
}
0 / 0
Hide Prices for Logged-Out Users

Hides product prices unless the user is logged in.

add_filter( 'woocommerce_get_price_html', 'smw_hide_price_logged_out' );
function smw_hide_price_logged_out( $price ) {
	if ( ! is_user_logged_in() ) {
		return '';
	}
	return $price;
}
0 / 0
Hide Admin Bar for Non-Admins

Hides the WordPress admin bar for users who are not administrators.

add_action( 'after_setup_theme', 'smw_hide_admin_bar' );
function smw_hide_admin_bar() {
	if ( ! current_user_can( 'administrator' ) ) {
		show_admin_bar( false );
	}
}
0 / 0
Limit Post Revisions

Limits the number of post revisions stored by WordPress.

define( 'WP_POST_REVISIONS', 5 );
0 / 0
Redirect Empty Search Queries

Redirects empty search queries back to the homepage.

add_action( 'template_redirect', 'smw_redirect_empty_search' );
function smw_redirect_empty_search() {
	if ( is_search() && empty( get_search_query() ) ) {
		wp_safe_redirect( home_url() );
		exit;
	}
}
0 / 0
Close Comments After 30 Days

Automatically closes comments on posts older than 30 days.

add_filter( 'comments_open', 'smw_close_old_comments', 10, 2 );
function smw_close_old_comments( $open, $post_id ) {
	if ( time() - get_post_time( 'U', true, $post_id ) > 30 * DAY_IN_SECONDS ) {
		return false;
	}
	return $open;
}
0 / 0
Disable Comment Author Links

Removes the website field and author links from comments.

add_filter( 'get_comment_author_link', 'smw_remove_comment_author_link' );
function smw_remove_comment_author_link( $link ) {
	return strip_tags( $link );
}
0 / 0
Allow Login with Username or Email

Lets users log in using either their username or email address.

add_filter( 'authenticate', 'smw_allow_email_login', 20, 3 );
function smw_allow_email_login( $user, $username, $password ) {

	if ( is_email( $username ) ) {
		$user_obj = get_user_by( 'email', $username );
		if ( $user_obj ) {
			$username = $user_obj->user_login;
		}
	}

	return wp_authenticate_username_password( null, $username, $password );
}
0 / 0
Redirect New Users After Registration

Sends newly registered users(on default WP registration) to a specific page after signup.

add_filter( 'registration_redirect', 'smw_registration_redirect' );
function smw_registration_redirect() {
	return home_url( '/welcome/' );
}
0 / 0
Customize WordPress Login Logo

Replaces the WordPress logo on the login screen with a custom image.

add_action( 'login_head', 'smw_custom_login_logo' );
function smw_custom_login_logo() {
	?>
	<style>
		#login h1 a {
			background-image: url('https://example.com/logo.png');
			background-size: contain;
			width: 100%;
		}
	</style>
	<?php
}
0 / 0
Customize WordPress Dashboard Logo

Replaces the WordPress logo in the admin dashboard header with a custom image.

add_action( 'admin_head', 'smw_custom_admin_logo' );
function smw_custom_admin_logo() {
	?>
	<style>
		#wp-admin-bar-wp-logo > .ab-item .ab-icon:before {
			background-image: url('https://example.com/logo.png');
			background-size: contain;
			background-position: center;
			background-repeat: no-repeat;
			color: transparent;
		}
	</style>
	<?php
}
0 / 0
Disable Automatic Updates

Stops WordPress from automatically updating core, plugins, and themes.

/**
 * Disable automatic updates
 *
 * This prevents WordPress from automatically updating
 * core, plugins, and themes.
 * Removing this snippet restores default update behavior.
 */

add_filter( 'automatic_updater_disabled', '__return_true' );
add_filter( 'auto_update_core', '__return_false' );
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );
0 / 0
Change “Out of Stock” Text

Customizes the text shown when a WooCommerce product is out of stock.

add_filter( 'woocommerce_get_availability_text', 'smw_change_out_of_stock_text', 10, 2 );
function smw_change_out_of_stock_text( $availability, $product ) {

	if ( ! $product->is_in_stock() ) {
		$availability = 'Sold out';
	}

	return $availability;
}
0 / 0
Disable Attachment Pages

Redirects WordPress attachment pages to the parent post or homepage.

/**
 * Disable attachment pages
 *
 * Redirects attachment pages (images, PDFs, etc.)
 * to their parent post, or to the homepage if no parent exists.
 * Removing this snippet restores default attachment pages.
 */

function smw_disable_attachment_pages() {
	if ( is_attachment() ) {
		global $post;

		if ( ! empty( $post->post_parent ) ) {
			wp_redirect( get_permalink( $post->post_parent ), 301 );
		} else {
			wp_redirect( home_url(), 301 );
		}
		exit;
	}
}
add_action( 'template_redirect', 'smw_disable_attachment_pages' );
0 / 0
Completely Disable Comments

Disables comments across the site and hides all comment-related UI.

/**
 * Completely disable comments site-wide
 *
 * This disables comments on posts and pages,
 * removes comment-related menu items,
 * and hides existing comment UI.
 * Removing this snippet restores comments.
 */

// Disable comments on all post types
add_filter( 'comments_open', '__return_false', 20, 2 );
add_filter( 'pings_open', '__return_false', 20, 2 );

// Hide existing comments
add_filter( 'comments_array', '__return_empty_array', 10, 2 );

// Remove comments page from admin menu
add_action( 'admin_menu', function() {
	remove_menu_page( 'edit-comments.php' );
} );

// Disable comments support for all post types
add_action( 'init', function() {
	foreach ( get_post_types() as $post_type ) {
		if ( post_type_supports( $post_type, 'comments' ) ) {
			remove_post_type_support( $post_type, 'comments' );
			remove_post_type_support( $post_type, 'trackbacks' );
		}
	}
} );

// Remove comments from admin bar
add_action( 'admin_bar_menu', function( $wp_admin_bar ) {
	$wp_admin_bar->remove_node( 'comments' );
}, 999 );
0 / 0
Disable Block Widgets (Use Classic Widgets)

Disables the block-based widgets editor and restores the classic widgets interface.

/**
 * Disable the block-based widgets editor
 *
 * Restores the classic widgets screen.
 * Removing this snippet re-enables block widgets.
 */

add_filter( 'use_widgets_block_editor', '__return_false' );
add_filter( 'gutenberg_use_widgets_block_editor', '__return_false' );
0 / 0
Disable Automatic Update Email Notifications

Stops WordPress from sending email notifications for automatic updates.

/**
 * Disable automatic update email notifications
 *
 * This prevents WordPress from sending emails after core, plugin,
 * or theme updates run automatically.
 */

add_filter( 'auto_core_update_send_email', '__return_false' );
add_filter( 'auto_plugin_update_send_email', '__return_false' );
add_filter( 'auto_theme_update_send_email', '__return_false' );
0 / 0
Disable Gutenberg Block Editor (use Classic Editor)

Disables the Gutenberg block editor and restores the classic editor experience.

/**
 * Disable the Gutenberg block editor
 *
 * Restores the classic editor for posts and pages.
 * Removing this snippet re-enables the block editor.
 */

add_filter( 'use_block_editor_for_post', '__return_false', 10 );
add_filter( 'use_block_editor_for_post_type', '__return_false', 10 );
0 / 0
Allow SVG Uploads (Admins Only)

Allows administrators to upload SVG files while keeping SVGs blocked for other users.

/**
 * Allow SVG uploads (admins only)
 *
 * SVG files can contain code, so it's safest to limit uploads to admins.
 * Removing this snippet restores the default behavior.
 */

add_filter( 'upload_mimes', 'smw_allow_svg_upload_admins_only' );
function smw_allow_svg_upload_admins_only( $mimes ) {

	if ( current_user_can( 'manage_options' ) ) {
		$mimes['svg'] = 'image/svg+xml';
	}

	return $mimes;
}
0 / 0
Change Default Gravatar Image

Sets a custom image as the default avatar for users without a Gravatar.

add_filter( 'avatar_defaults', 'smw_custom_default_gravatar' );
function smw_custom_default_gravatar( $avatar_defaults ) {

	$custom_avatar = get_stylesheet_directory_uri() . '/images/gravatar.png';
	$avatar_defaults[ $custom_avatar ] = 'Custom Default Avatar';

	return $avatar_defaults;
}
0 / 0
Duplicate Post or Page

Adds a “Duplicate” link to posts and pages for quick cloning.

/**
 * Duplicate post or page
 *
 * Adds a "Duplicate" link in the post/page list table
 * to quickly clone existing content.
 * Removing this snippet restores default behavior.
 */

function smw_duplicate_post_link( $actions, $post ) {
	if ( current_user_can( 'edit_posts' ) ) {
		$actions['duplicate'] = '<a href="' .
			wp_nonce_url(
				admin_url( 'admin.php?action=smw_duplicate_post&post=' . $post->ID ),
				'smw_duplicate_post_' . $post->ID
			) .
			'">Duplicate</a>';
	}
	return $actions;
}
add_filter( 'post_row_actions', 'smw_duplicate_post_link', 10, 2 );
add_filter( 'page_row_actions', 'smw_duplicate_post_link', 10, 2 );

function smw_duplicate_post() {
	if (
		empty( $_GET['post'] ) ||
		empty( $_GET['_wpnonce'] ) ||
		! wp_verify_nonce( $_GET['_wpnonce'], 'smw_duplicate_post_' . $_GET['post'] )
	) {
		wp_die( 'Invalid request.' );
	}

	$post_id = absint( $_GET['post'] );
	$post    = get_post( $post_id );

	if ( ! $post ) {
		wp_die( 'Post not found.' );
	}

	$new_post_id = wp_insert_post( [
		'post_title'   => $post->post_title . ' (Copy)',
		'post_content' => $post->post_content,
		'post_status'  => 'draft',
		'post_type'    => $post->post_type,
		'post_author'  => get_current_user_id(),
	] );

	// Copy taxonomies
	$taxonomies = get_object_taxonomies( $post->post_type );
	foreach ( $taxonomies as $taxonomy ) {
		$terms = wp_get_object_terms( $post_id, $taxonomy, [ 'fields' => 'ids' ] );
		wp_set_object_terms( $new_post_id, $terms, $taxonomy );
	}

	// Copy meta
	$meta = get_post_meta( $post_id );
	foreach ( $meta as $key => $values ) {
		foreach ( $values as $value ) {
			add_post_meta( $new_post_id, $key, maybe_unserialize( $value ) );
		}
	}

	wp_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
	exit;
}
add_action( 'admin_action_smw_duplicate_post', 'smw_duplicate_post' );
0 / 0