Archives: Snippets | Page 6

Exclude Pages from WordPress Search Results

To exclude pages from search results, add the following code to your functions.php file. You can also limit search to a specific Post Type by changing “post” on line 7 to the slug of the Post Type you want to display.

function filter_pages_from_search($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}

add_filter('pre_get_posts','filter_pages_from_search');

Conversely, to make WordPress search pages as well as posts, use this code:

function filter_pages_from_search($query) {
    if ($query->is_search) {
        $query->set('post_type', array('post', 'page'));
    }
    return $query;
}

add_filter('pre_get_posts','filter_pages_from_search');

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

Remove Product Reviews in WooCommerce

By default, the WooCommerce product page shows a “Reviews” tab that lets visitors leave reviews. If you want to remove the review system in WooCommerce on your WordPress site, add the following code to your functions.php file:


add_filter( 'woocommerce_product_tabs', 'sb_woo_remove_reviews_tab', 98);

function sb_woo_remove_reviews_tab($tabs) {
   unset($tabs['reviews']);
   return $tabs;
}

For more product page customization, see Edit Product Data Tabs in WooCommerce.

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.

Display Time Since Post Was Published in WordPress

A small snippet from the WordPress Codex that displays the time since a post was published.
Add the following code to your functions.php file:


/**
 * Display time since post was published
 *
 * @uses	human_time_diff()  Return time difference in easy to read format
 * @uses	get_the_time()  Get the time the post was published
 * @uses	current_time()  Get the current time
 *
 * @return	string  Timestamp since post was published
 *
 */
function get_time_since_posted() {

	$time_since_posted = 'Posted ' . human_time_diff( get_the_time( 'U' ), current_time( 'timestamp' ) ) . ' ago';

	return $time_since_posted;

}

Then add the function inside the loop where you want it:

echo get_time_since_posted();

For another useful post meta display, see Display Estimated Post Reading Time.

Set Custom Excerpt Word Count in WordPress

A simple function that sets the number of words returned when you call the the_excerpt function in WordPress. Add to functions.php and change the number on line 4 as needed.


function custom_excerpt_length( $length ) {
	return 40;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

This uses the excerpt_length filter hook. Learn more in WordPress Hooks Explained.

Remove the Submit Button in Gravity Forms

Gravity Forms is an excellent plugin for adding forms to your WordPress site. It lets you do this easily and quickly and includes many options for functional changes to forms.

For some reason, the plugin does not allow removing the Submit button from its forms, so if you want to use it and embed your own button you will need to remove the plugin’s default button. Add the following line to your functions.php file:

add_filter( 'gform_submit_button', '__return_false' );

For more form customization tips, see Restrict Free Emails in Forms.