Archives: Snippets | Page 8

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?.

Check if Current Page Is a Parent or Child Page

WordPress has a built-in function to check if you are on a specific page:

if ( is_page(5) ) {
        // do some stuff
    }

Or whether the page is a child of a specific page:

if ( $post->post_parent == '5' ) {
        // do some stuff
    }

But there is no built-in WordPress function that checks both conditions together, and this is very useful. For example – if we want to load a JS file for a videos page and all pages under it…

The following function (add to functions.php) creates a new logical function for this check:

function is_tree($the_page_id) {   
    global $post;         

    if(is_page()&&($post->post_parent==$the_page_id||is_page($the_page_id))) 
       return true;   
    else 
       return false;   
    };

Usage

if (is_tree(5)) {
        // do some stuff
    }

For more on WordPress page templates, see WordPress Template Hierarchy.

Set Default Post Status to Private in WordPress

The following code lets you set the default post status on your WordPress site to Private.

<?php 
function default_posts_to_private()
{
	global $post;

	if ( $post->post_status == 'publish' ) {
		$visibility = 'public';
		$visibility_trans = __('Public');
	} elseif ( !empty( $post->post_password ) ) {
		$visibility = 'password';
		$visibility_trans = __('Password protected');
	} elseif ( $post->post_type == 'post' && is_sticky( $post->ID ) ) {
		$visibility = 'public';
		$visibility_trans = __('Public, Sticky');
	} else {
		$post->post_password = '';
		$visibility = 'private';
		$visibility_trans = __('Private');
	} 
?>

	<script type="text/javascript">
		(function($){
			try {
				$('#post-visibility-display').text('<?php echo $visibility_trans; ?>');
				$('#hidden-post-visibility').val('<?php echo $visibility; ?>');
				$('#visibility-radio-<?php echo $visibility; ?>').attr('checked', true);
			} catch(err){}
		}) (jQuery);
	</script>
	<?php
add_action( 'post_submitbox_misc_actions' , 'default_posts_to_private' );

This uses a WordPress hook. Learn more in WordPress Hooks Explained.

Register Multiple Taxonomies in One Function

When working on a project that requires creating multiple taxonomies, it makes sense to use this function rather than creating a separate function for each taxonomy. Put each taxonomy’s parameters in the array and the function handles the rest:

<?php
/**
 * Register Multiple Taxonomies
 *
 */
function register_multiple_taxonomies() {
    $taxonomies = array(
        array(
            'slug'         => 'job-department',
            'single_name'  => 'Department',
            'plural_name'  => 'Departments',
            'post_type'    => 'jobs',
            'rewrite'      => array( 'slug' => 'department' ),
        ),
        array(
            'slug'         => 'job-type',
            'single_name'  => 'Type',
            'plural_name'  => 'Types',
            'post_type'    => 'jobs',
            'hierarchical' => false,
        ),
        array(
            'slug'         => 'job-experience',
            'single_name'  => 'Min-Experience',
            'plural_name'  => 'Min-Experiences',
            'post_type'    => 'jobs',
        ),
    );
    foreach( $taxonomies as $taxonomy ) {
        $labels = array(
            'name' => $taxonomy['plural_name'],
            'singular_name' => $taxonomy['single_name'],
            'search_items' =>  'Search ' . $taxonomy['plural_name'],
            'all_items' => 'All ' . $taxonomy['plural_name'],
            'parent_item' => 'Parent ' . $taxonomy['single_name'],
            'parent_item_colon' => 'Parent ' . $taxonomy['single_name'] . ':',
            'edit_item' => 'Edit ' . $taxonomy['single_name'],
            'update_item' => 'Update ' . $taxonomy['single_name'],
            'add_new_item' => 'Add New ' . $taxonomy['single_name'],
            'new_item_name' => 'New ' . $taxonomy['single_name'] . ' Name',
            'menu_name' => $taxonomy['plural_name']
        );
        
        $rewrite = isset( $taxonomy['rewrite'] ) ? $taxonomy['rewrite'] : array( 'slug' => $taxonomy['slug'] );
        $hierarchical = isset( $taxonomy['hierarchical'] ) ? $taxonomy['hierarchical'] : true;
    
        register_taxonomy( $taxonomy['slug'], $taxonomy['post_type'], array(
            'hierarchical' => $hierarchical,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => $rewrite,
        ));
    }
    
}
add_action( 'init', 'register_multiple_taxonomies' );

Split WordPress Loop Posts into Groups

In my last project I needed to split the WordPress loop into groups of three posts – so if there are nine posts, every three would be wrapped in a div. You can do this using a counter and checking inside the loop whether it is a multiple of 3, and if so, closing the div. To change the number of posts per group, change the number 3 on line 14. Here is the code:

<?php if ( have_posts() ) :
	$i = 0;
	while ( have_posts() ) : the_post();
		if ( $i % 3 == 0 ) { ?>
			<div>
	<?php } ?>
			<div class="single_item">
				<h2>
					<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>
					</a>
				</h2>
			</div>
	<?php $i ++;
		if ( $i % 3 == 0 ) { ?>
			</div>
	<?php } ?>

	<?php endwhile; ?>
	<?php
	if ( $i % 3 != 0 ) { ?>
		</div>
	<?php } ?>

<?php endif; ?>

For more loop customization, see Remove a Category from the Main Loop.

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.

Move the WordPress Admin Bar to the Bottom

More than once the WordPress admin bar has bothered me because it hid menus that were set to position:fixed in CSS. A few lines in functions.php and the admin bar moves to the bottom of the page:

function fb_move_admin_bar() { ?>
	<style type="text/css">
		body {
			margin-top: -28px;
			padding-bottom: 28px;
		}
		body.admin-bar #wphead {
			padding-top: 0;
		}
		body.admin-bar #footer {
			padding-bottom: 28px;
		}
		#wpadminbar {
			top: auto !important;
			bottom: 0;
		}
		#wpadminbar .quicklinks .menupop ul {
			bottom: 28px;
		}
	</style>
<?php }
add_action( 'admin_head', 'fb_move_admin_bar' );
add_action( 'wp_head', 'fb_move_admin_bar' );

For safe WordPress customizations, see What Are Child Themes and How to Use Them.

Hide the Sitemap from Search Engines

The Sitemap file helps search engines index your site and find the most important pages easily. If you do not want the Sitemap to appear in Google search results, add the following lines to the .htaccess file in the root directory where WordPress is installed:

<IfModule mod_rewrite.c>
 <Files sitemap.xml>
    Header set X-Robots-Tag "noindex"
 </Files>
 </IfModule>

Replace sitemap.xml with your Sitemap file name. For more on what a Sitemap is, see the post How to create a Sitemap in WordPress and how to submit it via Google Search Console.