search ]

Archives: Snippets | Page 6

Redirect to Maintenance Page in WordPress

There are several plugins that show visitors a temporary message that your WordPress site is in maintenance mode, such as this plugin. It is a great plugin when you are developing the site or performing a temporary update, but these plugins will not help if your site goes down for any reason – they only work when the site is running properly. For when WordPress gets stuck in maintenance mode during updates, see how to fix WordPress maintenance mode.

In such cases it is worth preparing a permanent maintenance page on your server and redirecting visitors to it when your site goes down.

Add the following lines to your .htaccess file. Note that you need to change the address on line 3 to your IP so you can still access the site. Also change the page name and location according to your setup on line 3.

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123.123.123.123
RewriteRule $ /maintenance.html [R=302,L]

Auto Redirect to Post on Single Search Result

This snippet causes a redirect to the post when a WordPress search returns only one result, instead of displaying the search results page as usual.

function single_result() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
        }
    }
}

add_action('template_redirect', 'single_result');

For more on WordPress search optimization, see Prevent Search Engines from Indexing Search Results.

Style Anchor Tags by Link Type with CSS

This code aims to improve user experience. We often encounter situations where we click links without knowing where they lead. This code can improve UX by adding small icons next to links to show visitors that it is an external link – email, PDF file, image, etc.

/* external links */
a[href^="http://"]{
    padding-right: 20px;
    background: url(external.gif) no-repeat center right;
}
 
/* emails */
a[href^="mailto:"]{
    padding-right: 20px;
    background: url(email.png) no-repeat center right;
}
 
/* pdfs */
a[href$=".pdf"]{
    padding-right: 20px;
    background: url(pdf.png) no-repeat center right;
}

For more on link styling, see Styling External Links with CSS.

Redirect WWW to Non-WWW and Vice Versa via HTACCESS

If you want to redirect all URLs on your site that contain www to the non-www version (e.g. http://www.my-domain.com to http://my-domain.com), add the following code to your .htaccess file:


RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

If you want to do the opposite – redirect non-www URLs to the www version – use this code:


RewriteEngine On
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Why do this?

  • Prevents Google from treating these as two separate URLs (duplicate content).
  • Prevents your page ranking from being split across two URLs.
  • It is cleaner and more consistent.

Migrating a WordPress site to HTTPS is no small matter – see the guide Migrating to HTTPS on WordPress sites.

Prevent Image Hotlinking via HTACCESS

Tired of people using your bandwidth by linking to your images on their sites? This annoying phenomenon is called hotlinking. Prevent image hotlinking by adding the following code at the bottom of your .htaccess file and replace the domain name with yours:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?example.com/.*$ [NC] 
RewriteRule .(gif|jpg)$ http://www.example.com/hotlink.gif [R,L]

For more security tips, see Hardening WordPress Security.

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

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.

Savvy WordPress Development official logo