search

Archives: Snippets | Page 9

Change WordPress Auto-Save Interval

When you write a post, it is automatically saved as a draft every minute. If your browser crashes this lets you recover your work. You can change the time between saves by adding the following line to your wp-config.php file:

define( 'AUTOSAVE_INTERVAL', X);

Where X is the number of seconds between saves.

For more wp-config.php settings, see Optimize WordPress Configuration via wp-config.php.

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:

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

Block Search Engines from Indexing Directories

You want search engines to index your blog pages but not the PHP files of your WordPress installation. Edit the robots.txt file and add the following lines to block search engines from indexing these files:

User-agent: *
Disallow: /wp-admin/
Disallow: /wp-includes/
Disallow: /wp-content/plugins/
Disallow: /wp-content/themes/
Disallow: /feed/
Disallow: */feed/

For more on managing search engine access, see Create and Send a Sitemap for WordPress SEO.

Get the Top-Level Parent Category of a Post

The following snippet is useful if you want to get the top-level parent category in the hierarchy of a post. Add the following code to your functions.php file:


function get_top_category() {

    $cats = get_the_category();
    $top_cat_obj = array();

    foreach($cats as $cat) {
        if ($cat->parent == 0) {
            $top_cat_obj[] = $cat;
        }
    }
    $top_cat_obj = $top_cat_obj[0];

    return $top_cat_obj;
}

Usage: $top_cat = get_top_category(); echo $top_cat->slug;

For more on taxonomies and categories, see How to Create Custom Post Types.

Add Custom Fields to User Profile in WordPress

Place the following code in your functions.php file to add custom fields to the user profile page in WordPress:

function my_custom_userfields( $contactmethods ) {

        $contactmethods['contact_phone_office']     = 'Office Phone';
        $contactmethods['contact_phone_mobile']     = 'Mobile Phone';
        $contactmethods['contact_office_fax']       = 'Office Fax';
    
        $contactmethods['address_line_1']       = 'Address Line 1';
        $contactmethods['address_line_2']       = 'Address Line 2 (optional)';
        $contactmethods['address_city']         = 'City';
        $contactmethods['address_state']        = 'State';
        $contactmethods['address_zipcode']      = 'Zipcode';
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);

For a more advanced approach to custom fields, see Beginner’s Guide to Advanced Custom Fields.

Include Custom Post Types in Search Results

The following code will make Custom Post Types on your WordPress site appear in search results:


function searchAll( $query ) {
    if ( $query->is_search ) { $query->set( 'post_type', array( 'site', 'plugin', 'theme', 'person' )); }
     return $query;
}

add_filter( 'the_search_query', 'searchAll' );

Change line 4 to the post types you want.

Hide WordPress Update Notices for Non-Admin Users

The following code ensures that no user logged into the WordPress dashboard will see WordPress version update notices:


    global $user_login;
    get_currentuserinfo();
    
    if ($user_login !== "admin") {
        add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
        add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
    }

Change “admin” to the username that should receive updates.

Alternative version that shows the update notice to all site administrators, not just the user named “admin”:


    global $user_login;
    get_currentuserinfo();
    
    if (!current_user_can('update_plugins')) {
          add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 );
          add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );
    }

This uses WordPress hooks. Learn more in WordPress Hooks Explained.

Prevent WordPress from Creating Default Image Sizes

Every time you upload an image to the media library, WordPress saves it in several default sizes. Usually this is fine, but there are many cases where you do not need those images – for example if you use or define your own image sizes in your theme.

In such cases it makes sense to prevent WordPress from creating these images since they take up server space unnecessarily. To remove default image sizes in WordPress, add the following code to your functions.php file:

function wcr_remove_intermediate_image_sizes($sizes, $metadata) {
    $disabled_sizes = array(
        'thumbnail',
        'medium',
        'large'
    );

    foreach ($disabled_sizes as $size) {
        if (!isset($sizes[$size])) {
            continue;
        }
    
        unset($sizes[$size]);
    }

    return $sizes;
}

add_filter('intermediate_image_sizes_advanced', 'wcr_remove_intermediate_image_sizes', 10, 2);

For a broader guide on this topic, see the article on image sizes in WordPress.

Savvy WordPress Development official logo