Archives: Snippets | Page 8

Add Google Fonts to WordPress

There are several ways to add Google Fonts to a WordPress site. Here are two of them. The first and less recommended option is to add the fonts directly to your theme’s header.php (preferably in a child theme).

<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Lora|Oswald" media="screen">

When using this method, note that you must add the Google Fonts call before you load the main stylesheet.

The second and more recommended option is using wp_register_style and wp_enqueue_style. Add the following code to your functions.php file:


function add_my_google_fonts() {

	wp_register_style('my-googleFonts', 'https://fonts.googleapis.com/css?family=Open+Sans:300italic,300,600,700,400');
    wp_enqueue_style( 'my-googleFonts');
}
add_action('wp_enqueue_scripts', 'add_my_google_fonts');

Avoid making two or more calls to Google’s servers – you can embed all fonts in a single call.

There is also an option for local embedding of Google fonts. Local embedding has several advantages – for more on this, see the post Loading Google Fonts locally.

Set Minimum Comment Length in WordPress

If you do not want short comments on your posts such as “Thanks!” or “Great article…“, add the following code to your functions.php file and set the minimum character count on line 4:


function minimal_comment_length( $commentdata ) {
    $minimalCommentLength = 20;
    if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength ) {

        wp_die( 'Your comment must contain at least ' . $minimalCommentLength . ' characters.' );

    }

    return $commentdata;
}
add_filter( 'preprocess_comment', 'minimal_comment_length' );

For more comment management, see Show the Total Number of Comments.

Hide a Product Category from WooCommerce Shop

To hide a product category from your WooCommerce shop, add the following code to your functions.php file and replace xxxxxx with the slug of the category you want to hide:


function custom_pre_get_posts_query( $q ) {
 
	if ( ! $q->is_main_query() ) return;
	if ( ! $q->is_post_type_archive() ) return;
	
	if ( ! is_admin() && is_shop() ) {

		$q->set( 'tax_query', array(array(
			'taxonomy' => 'product_cat',
			'field' => 'slug',
			'terms' => array( 'xxxxxx' ),
			'operator' => 'NOT IN'
		)));
	
	}
 
	remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
 
}
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

For more on WooCommerce categories, see Check if a Product Belongs to a Specific Category.

Change the Login Page Logo and Link in WordPress

The following code lets you change the logo on the WordPress login page as well as the link it points to:

add_filter( 'login_headerurl', 'namespace_login_headerurl' );
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}
add_filter( 'login_headertitle', 'namespace_login_headertitle' );

function namespace_login_style() {
    echo '<style>.login h1 a { background-image: url( ' . get_template_directory_uri() . '/images/logo.png ) !important; }</style>';
}
add_action( 'login_head', 'namespace_login_style' );

For more login page security tips, see Hardening WordPress Security.

Show All Settings Page in WordPress Dashboard

This snippet does something neat – it adds an option under the Settings menu with a link named “All Settings” that shows a full list of all settings in the database related to your WordPress site.

The code below shows this option only to site administrators and hides it from other users.


function all_settings_link() {
   add_options_page(__('All Settings'), __('All Settings'), 'administrator', 'options.php');
}

add_action('admin_menu', 'all_settings_link');

For a broader WordPress overview, see What is WordPress?.

Remove Website Field from WordPress Comment Form

There are situations where the “Website” (or URL) field is not needed in the comment form. In such cases, remove the field by adding the following code to your functions.php file:

/**
 * Remove the URL field
 *
 * @param array $fields
 *
 * @return array
 */
function sv_comment_form_default_fields( $fields ) {
	if ( isset( $fields['url'] ) ) {
		unset( $fields['url'] );
	}

	return $fields;
}

add_filter( 'comment_form_default_fields', 'sv_comment_form_default_fields' );

If you use a child theme, add this code to your child theme’s functions.php file.

Change JPEG Compression Quality in WordPress

WordPress generates several image sizes according to your theme settings. These images are created at quality 90 on a scale of 1-100 by default. You can save bandwidth by changing this setting to 75 for more aggressive compression.

/**
 * Snippet Name: Change jpg compression level
 */
function sv_jpeg_quality() {
	return 75;
}
add_filter( 'jpeg_quality', 'sv_jpeg_quality' );

For more on optimizing images for WordPress, see optimizing WordPress images for SEO.

Remove Sticky Posts from the Main Loop

We use the pre_get_posts hook to modify the main loop and tell it to ignore sticky posts. Note that this removes them from the blog’s main loop entirely, not just from the top. If you want to display them, you will need to write your own loop above the main loop that only queries those sticky posts:

/**
 * Snippet Name: Remove sticky posts from the main query
 */
function sv_ignore_sticky( $query ) {
	if ( ! is_admin() && $query->is_home() && $query->is_main_query() ) {
		$query->set( 'ignore_sticky_posts', true );
		$query->set( 'post__not_in', get_option( 'sticky_posts' ) );
	}
}

add_action( 'pre_get_posts', 'sv_ignore_sticky' );

The condition limits the change to the main query on the blog home page, so sticky posts still show in widgets, custom loops and the admin. ignore_sticky_posts on its own only stops them from being moved to the top. post__not_in is what removes them from the list.

Change WordPress Auto-Save Interval

Yes, WordPress autosaves your work. While you edit a post with unsaved changes, it saves a copy every 60 seconds by default, in both the block editor and the classic editor. If the browser crashes or the connection drops, you can restore that copy.

The AUTOSAVE_INTERVAL constant controls how often that happens. Raise it for fewer saves to the server, or lower it if losing even a minute of writing is too much.

Change the Autosave Interval

Add this line to wp-config.php, above the /* That's all, stop editing! */ line. The value is in seconds.

define( 'AUTOSAVE_INTERVAL', 120 );

This example saves every 2 minutes. It has to go above that line because WordPress sets its own default of 60 seconds right after, but only if the constant isn’t already defined.

How Autosave Works in Each Editor

Both editors read the same constant, but they send the autosave differently.

  • Block editor: passes AUTOSAVE_INTERVAL to the editor settings and saves through the REST API autosaves endpoint.
  • Classic editor: sends autosaves with the Heartbeat API. If you disable Heartbeat on the post edit screen to reduce server load, classic autosave stops too.

The block editor also keeps a backup in the browser’s sessionStorage every 15 seconds. That local copy is separate from AUTOSAVE_INTERVAL and never reaches the server.

Autosaves vs Revisions

An autosave isn’t a regular revision, and the rules depend on the post status and who is editing.

  • Your own draft: the autosave overwrites the draft itself. No extra row is created.
  • A published post, or another user’s draft: the autosave is stored in wp_posts as a revision named {post_ID}-autosave-v1. There is one per user per post, overwritten on each save.

When WordPress trims old revisions down to the WP_POST_REVISIONS limit, it never deletes autosaves. Setting WP_POST_REVISIONS to false doesn’t turn autosave off either.

Since there is at most one autosave per user per post, a longer interval barely affects database size. To control revision growth, limit the number of post revisions or disable post revisions instead.

Choosing a Value

The default of 60 seconds suits most sites. A few cases justify changing it:

  • Several editors working at once on shared hosting: 120 to 300 seconds means fewer autosave writes. In the classic editor, Heartbeat requests continue on their own schedule.
  • Long-form writing where every paragraph matters: 30 seconds. Each autosave replaces the previous one, so the database doesn’t grow.

For other constants worth setting in the same file, see Optimize WordPress Configuration via wp-config.php.

FAQs

Common questions about WordPress autosave:

Does WordPress autosave posts?
Yes. When there are unsaved changes, WordPress autosaves every 60 seconds by default. Change the interval with the AUTOSAVE_INTERVAL constant in wp-config.php.
Where does WordPress store autosaves?
In the wp_posts table. Drafts you own are overwritten in place, while autosaves of published posts are stored as a revision post named {post_ID}-autosave-v1, one per user.
Can I disable autosave completely?
There is no core setting for it. A very large AUTOSAVE_INTERVAL, such as 86400, effectively stops server autosaves, but the block editor's local browser backup keeps running. Losing unsaved work is usually a bigger problem than the extra saves.
Does AUTOSAVE_INTERVAL affect the Customizer?
Yes. The Customizer uses the same constant for how often it autosaves unpublished changes in the current changeset.