search

Code Snippets

We all agree that WordPress plugins are useful and simplify many situations. But sometimes a few lines in your theme's functions.php file can save you from adding yet another plugin to your site.

In this archive you'll find a wide variety of code snippets that allow modifications and customizations to WordPress and how it works. These are short, practical code snippets collected over the years.

Every time I come across a useful snippet I add it to the collection, so if you have a specific snippet you'd like to share, feel free to send it over and I'll add it to the list.

Hide Out of Stock Products in WooCommerce

You can hide out-of-stock products from catalog and search pages. The simplest way is through WooCommerce settings: WooCommerce > Settings > Products > Inventory > “Hide out of stock items from the catalog”. If you prefer a code-based approach, add to your functions.php. For more on managing stock in WooCommerce.

add_action( 'pre_get_posts', function( $query ) {
	if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) {
		$query->set( 'meta_query', array(
			array(
				'key'     => '_stock_status',
				'value'   => 'instock',
				'compare' => '=',
			),
		) );
	}
} );

Disable Pingbacks and Trackbacks in WordPress

Pingbacks and trackbacks are a legacy WordPress mechanism that notifies other sites when you link to them. In practice, most pingbacks are spam and there is no reason to keep the feature enabled. For more on hardening WordPress security.

Disable pingbacks via code – add to functions.php:

add_filter( 'xmlrpc_methods', function( $methods ) {
	unset( $methods['pingback.ping'] );
	unset( $methods['pingback.extensions.getPingbacks'] );
	return $methods;
} );

add_action( 'pre_ping', function( &$links ) {
	$home = get_option( 'home' );
	foreach ( $links as $l => $link ) {
		if ( strpos( $link, $home ) === 0 ) {
			unset( $links[ $l ] );
		}
	}
} );

Also disable the option in Settings > Discussion > uncheck “Allow link notifications from other blogs (pingbacks and trackbacks)”.

Change Currency Symbol in WooCommerce

If you want to change the currency symbol WooCommerce displays (e.g. replace “$” with “USD” or add a space), add the following code to your functions.php file. For more on WooCommerce hooks.

add_filter( 'woocommerce_currency_symbol', function( $symbol, $currency ) {
	switch ( $currency ) {
		case 'USD':
			$symbol = 'USD ';
			break;
		case 'GBP':
			$symbol = 'GBP ';
			break;
	}
	return $symbol;
}, 10, 2 );

Modify the case and $symbol values to match your needs.

Add a Custom WP-Cron Interval in WordPress

WordPress ships with three WP-Cron intervals: hourly, twicedaily, and daily. If you need a different interval (e.g. every 5 minutes), add the following code. For more on WordPress hooks and filters.

add_filter( 'cron_schedules', function( $schedules ) {
	$schedules['every_five_minutes'] = array(
		'interval' => 300,
		'display'  => 'Every 5 Minutes',
	);
	return $schedules;
} );

// Schedule the event on theme activation
if ( ! wp_next_scheduled( 'my_custom_cron_event' ) ) {
	wp_schedule_event( time(), 'every_five_minutes', 'my_custom_cron_event' );
}

add_action( 'my_custom_cron_event', function() {
	// Your code here
} );

Increase WordPress Upload Max File Size

WordPress limits the file size you can upload through the Media Library. The limit is set by PHP settings on the server. Here are three ways to increase it. For more on troubleshooting image upload errors.

Option 1 – .htaccess file:

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

Option 2 – wp-config.php file:

@ini_set( 'upload_max_filesize', '64M' );
@ini_set( 'post_max_size', '64M' );
@ini_set( 'max_execution_time', '300' );

Option 3 – php.ini file:

upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300

Replace 64M with your desired size.

Increase WordPress Memory Limit

If you encounter the “Allowed memory size exhausted” error, increase the WordPress memory limit. Add the following lines to your wp-config.php file before the “That’s all, stop editing!” line. For more on optimizing wp-config.php.

define( 'WP_MEMORY_LIMIT', '256M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );

WP_MEMORY_LIMIT affects the frontend and WP_MAX_MEMORY_LIMIT affects the admin area. If the change does not help, your hosting provider may enforce a server-level limit.

Set Minimum Order Amount in WooCommerce

If you want to require a minimum order amount in your WooCommerce store, add the following code to your functions.php file. The code displays a notice in the cart and prevents checkout. For more on WooCommerce hooks.

add_action( 'woocommerce_checkout_process', function() {
	$minimum = 50;
	if ( WC()->cart->get_subtotal() < $minimum ) {
		wc_add_notice(
			sprintf( 'The minimum order amount is %s. Your current cart total is %s.',
				wc_price( $minimum ),
				wc_price( WC()->cart->get_subtotal() )
			), 'error'
		);
	}
} );

add_action( 'woocommerce_before_cart', function() {
	$minimum = 50;
	if ( WC()->cart->get_subtotal() < $minimum ) {
		wc_print_notice(
			sprintf( 'The minimum order amount is %s. Please add more products to your cart.',
				wc_price( $minimum )
			), 'notice'
		);
	}
} );

Replace 50 with your desired minimum amount.

Remove Related Products in WooCommerce

WooCommerce displays related products at the bottom of the product page by default. To remove them, add the following code to your functions.php file. For more on WooCommerce hooks.

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );

If you only want to change the number of related products displayed instead of removing them entirely:

add_filter( 'woocommerce_output_related_products_args', function( $args ) {
	$args['posts_per_page'] = 3;
	$args['columns'] = 3;
	return $args;
} );

Force HTTPS Redirect via .htaccess in WordPress

After installing an SSL certificate, add the following code to your .htaccess file to redirect all traffic from HTTP to HTTPS. For more on migrating your WordPress site to HTTPS.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Make sure the code is placed at the top of your .htaccess file, before the existing WordPress rules.

Disable WP-Cron and Use a Real Server Cron Job

WP-Cron runs on every page load, which can cause overhead on high-traffic sites or missed events on low-traffic sites. You can disable it and use a real server cron job instead. For more on optimizing wp-config.php.

Step 1 – Add to wp-config.php:

define( 'DISABLE_WP_CRON', true );

Step 2 – Set up a server cron job (every 5 minutes):

*/5 * * * * wget -q -O /dev/null https://your-domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

Replace your-domain.com with your domain.

Savvy WordPress Development official logo