Here are 17+ valuable WordPress snippets for a site-specific plugin and functions.php file that provides you a better WordPress experience. Enhance your WordPress site with these small PHP snippets: WordPress filters, actions and functions. Quickly add or extend the functionality you need for your WordPress website! Read on…

Extending your WordPress blog with plugins can greatly improve the speed, performance and security of your website

A few years ago I wrote a post that summed up 9 WordPress plugins you’ll need for your WordPress site, to extend its speed & performance, functionality, security and user experience.

Last year I wrote a post – in Dutch – with my WordPress plugins must-haves (Google translation of the article). This post is not about plugins, it’s about useful and valuable WordPress code snippets.

Credit where credit is due, some snippets aren’t mine. Whenever I could find – or remember – the original author, he or she is credited (some snippets are rather old, collecting dust in my archives, and hardly nowhere to be found anymore).

I’ll update this post and add more snippets if – and when – I see fit.

So stay tuned! (-:

#1: Redirect to another website after a WordPress login failure

WPBeginner wrote a small post on disabling WordPress Login Hints. WordPress login hints is a message telling you your WordPress username and/or password is (are) wrong, during login.

The WordPress filter code snippet to your themes functions.php file or a site-specific plugin (blatantly copied here), to change the WordPress login hints is:

<?php
function no_wordpress_errors(){
  return 'Something is wrong!';
}
add_filter( 'login_errors', 'no_wordpress_errors' );

This made me decide to play with this filter function: is it possible to redirect a visitor after a failed login in WordPress? Yes, it is! Here’s my modified snippet you can use to redirect users after a login failure:

<?php
function saotn_redirect_after_login_errors() {
  return header('Location: http://www.example.com/');
  // or use WordPress' wp_redirect functionality:
  // wp_redirect( 'http://www.example.com/' );
  exit;
}
add_filter( 'login_errors', 'saotn_redirect_after_login_errors' );

Find out more about wp_redirect.

This will redirect an user to example.com whenever he/she tries to log on using invalid credentials. I have a Dutch article explaining why you must not use a delay (or PHP sleep();) in your WordPress login to prevent brute-force attacks. Just Google Translate the article.

I’m not sure a redirect is a good alternative though…

My colleague Pieter created a plugin PD Login Security, that:

Disables the default login errors, adding more security to the login form of your WordPress install.

https://wordpress.org/plugins/pd-login-security/

The following three snippets are specifically for the WordPress theme Enfold, or any other theme using similar code. BTW, I’m in no way associated with Kriesi.

#2: Adding WhatsApp Button on Social Share Buttons

You can easily extend the Enfold social share buttons, beneath every post, with a WhatsApp share button. Add the following three (3) filter functions to your functions.php file:

<?php // Register new icon as a theme icon
add_filter( 'avf_default_icons','avia_add_custom_icon', 10, 1 );
function avia_add_custom_icon($icons) {
  $icons['whatsapp'] = array( 'font' =>'whatsapp-font-icon', 'icon' => 'ue800');
  return $icons;
}

// Adjust icons
add_filter( 'avia_filter_social_icons', 'avia_filter_social_icons_mod', 10, 1 );
function avia_filter_social_icons_mod($icons) {
  $icons['Whatsapp'] = 'whatsapp';
  return $icons;
}

// Add items on the social share section
add_filter( 'avia_social_share_link_arguments', 'avia_add_social_share_link_arguments', 10, 1 );
function avia_add_social_share_link_arguments($args)
{
  $args['whatsapp'] = array("encode"=>true,
    "encode_urls"=>false,
    "pattern" => "whatsapp://send?text=[title]&url=[permalink]",
    "label" => __( "Share on Whatsapp", 'avia_framework' )
    );
  return $args;
}

Using this, you can share your posts via WhatsApp, neat! 🙂

Source: Kriesi Enfold Support – Adding WhatsApp Button on Social Share Buttons, Re Adding WhatsApp Button on Social Share Buttons.

#3: Load Facebook Like Box Asynchronously

This one is not only for the Enfold theme, but for any WordPress theme using similar code (Rise of ThriveThemes being one of them).

Asynchronously loading the Facebook Like Box speeds up the loading of your WordPress website: The external resources are loaded asynchronously (async), or in parallel, meaning they don’t block the browser. A lot of WordPress themes provide widgets like these Facebook Like Boxes, and it’s important to load the scripts async for the reason I stated above.

This may interest you:   Tips to speed up WordPress, serve gzip compressed static HTML files

Note: This often involves making a change to a theme file. It’ll be overwritten during a theme update, if you don’t use a child-theme, please keep that in mind.

First you need to look up where the Facebook Like Box JavaScript code resides, for Enfold it is in framework/php/class-framework-widgets.php. Add js.async=true; around line 80, and the complete Facebook JavaScript then becomes:

<?php
function fb_js() {
  if(self::$script_loaded == 1) return;
  self::$script_loaded = 1;
  echo '
    <script>(function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0]; 
      if (d.getElementById(id)) return; 
      js = d.createElement(s); js.id = id; 
      js.async = true; 
      js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.4"; 
      fjs.parentNode.insertBefore(js, fjs); 
    }
    (document, "script", "facebook-jssdk"));</script> 
  '; 
}

#4: Load all JavaScripts Asynchronously; How to Add “async” Attribute (Bonus!)

It’s recommended to load as many JavaScript files asynchronously in WordPress. An easy function to load all JavaScript files async is as follows:

<?php
// http://matthewhorne.me/defer-async-wordpress-scripts/
function saotn_add_async_attribute( $tag, $handle ) {
  $scripts_to_async = array( 'google-adsense',      // example handles
    'jquery-sonar', 
    'jquery', 
    'dsq_embed_script', 
    'wpcom-lazy-load-images', 
    'dsq_count_script' );
  foreach( $scripts_to_async as $async_script ) {
    if ( $async_script === $handle ) {
        return str_replace( ' src', ' async="async" src', $tag );
    }
  }
  return $tag;
}
add_filter( 'script_loader_tag', 'saotn_add_async_attribute', 10, 2 );

Add the script handles of scripts you want to load async in the $scripts_to_async array.

#5: Defer JavaScripts

Some JavaScripts need to load async, but some needs to load deferred. This is how:

// http://matthewhorne.me/defer-async-wordpress-scripts/
function saotn_add_defer_attribute( $tag, $handle ) {
  $scripts_to_defer = array( 'prismjs',     // example handles
    'sparkling-functions', 
    'sparkling-bootstrapjs', 
    'sparkling-modernizr', 
    'sparkling-skip-link-focus-fix'
  );
  foreach( $scripts_to_defer as $defer_script ) {
    if ( $defer_script === $handle ) {
        return str_replace( ' src', ' defer="defer" src', $tag );
    }
  }
  return $tag;
}
add_filter( 'script_loader_tag', 'saotn_add_defer_attribute', 10, 2 );

#6: Add additional Google fonts for heading and content in Enfold

So you want to prettify your fonts, and add some fonts Enfold may be lacking? Here’s a quick code snippet to add Ubuntu, OpenSans and Merriweather to your Enfold theme.

Add the following code directly below if(isset($avia_config['use_child_theme_functions_only'])) return; in your functions.php file:

<?php
add_filter( 'avf_google_heading_font',  'avia_add_heading_font');
function avia_add_heading_font($fonts) {
  $fonts['Open+Sans700400'] = 'Open+Sans:700,400';
  $fonts['Ubuntu400400'] = 'Ubuntu:400,400italic,500';
  return $fonts;
}
add_filter( 'avf_google_content_font',  'avia_add_content_font' );
function avia_add_content_font($fonts) {
  $fonts['Merriweather'] = 'Merriweather:300,700,700italic,300italic';
  $fonts['Ubuntu'] = 'Ubuntu:400,400italic,500';
  return $fonts;
}

#7: Remove PHP Sessions in Enfold

Enfold by Kriesi creates a lot of session files on your server. This may clog and slow down your site. The PHP sessions in Enfold are used for breadcrumbs. If you use the portfolio grid for example, sessions are used to save data for each user to track where they came from. This is then used to dynamically generate breadcrumbs.

If you are OK with not having these breadcrumbs (perhaps you’re using Yoast?), or you’re not using the portfolio grid, and you want to speed up your WordPress site, then you can use the following in your Enfold theme functions.php file:

add_theme_support( 'avia_no_session_support' );

This disables PHP session support in the premium theme Enfold.

#8: Load default WordPress jQuery from Google Library

Change jQuery URL or version by using Google’s CDN

Sometimes you run into problems with jQuery, and you need to temporarily change the jQuery version in use. It’s best to then load the jQuery JavaScript file from Google API, so you can change versions quickly:

<?php
// Available jQuery versions: https://code.jquery.com/jquery/
function modify_jquery() {
  if (!is_admin()) {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', false, '2.1.4', true );
    wp_enqueue_script( 'jquery' );
  }
}
add_action( 'wp_enqueue_scripts', 'modify_jquery' );

The final true loads jQuery in the WordPress footer, near </body>, this may cause unexpected behaviour. Set it to false, or remove it since false is the default, to load jQuery in your header.

#9: Remove jQuery Migrate

DIYthemes writes in a blog post:

jQuery migrate is used to load any deprecated APIs and functions that were removed in jQuery 1.9, so if you do not use any of those deprecated functions (read here for information on what changed in 1.9), you can remove jQuery migrate and save a time-consuming request to your server.

Here’s the function for your site-specific plugin or functions.php file:

/* http://diythemes.com/thesis/3-performance-tips/
 * Remove jquery migrate for enhanced performance
 */
function remove_jquery_migrate($scripts) {
   if ( is_admin() ) return;
   $scripts->remove( 'jquery' );
   $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.10.2' );
}
add_action( 'wp_default_scripts', 'remove_jquery_migrate' );

#10: Clean expired transients behind the scenes – by Pressjitsu

Keeping your MySQL database small (lean & mean) is important for a fast operating database. Pressjitsu open-sourced and released their plugin to automatically clean expired transients from your database. This keeps your database smaller and faster.

This may interest you:   add_rewrite_rule() accepts an array of query vars in WordPress 4.4

You may find its source on Pressjitsu’s GitHub, I used this as a basis for my plugin to regularly perform an OPTIMIZE TABLES statement on my MySQL database. They both utilize WordPress Cron.

#11: Prefetch & prerender WordPress’ next and previous posts

When a lot of your readers click through to your next or previous post, then you can speed up the loading and rendering of these posts by utilizing HTML5’s prefetch & prerender link attributes – also known as resource hints.

When defined, they tell your browser to start loading the given URL to render it in the background. This should give your visitors a near instant load when they click through.

In your site-specific plugin or functions.php, add the following function:

<?php
function saotn_post_prerender_prefetch() {
  /* follow me on Twitter: @HertogJanR */
  $next_post = get_next_post();
  $prev_post = get_previous_post();
  if ( !empty( $next_post ) ) {
    echo '<link rel="prefetch" href="'.get_permalink( $next_post->ID ).'" />
      <link rel="prerender" href="'.get_permalink( $next_post->ID ).'" />';
  }
  if ( !empty( $prev_post ) ) {
    echo '<link rel="prefetch" href="'.get_permalink( $prev_post->ID ).'" />
      <link rel="prerender" href="'.get_permalink( $prev_post->ID ).'" />';
  }
}
add_action( 'wp_head', 'saotn_post_prerender_prefetch', 10 );

Note: You might have guessed: This only works when visitors do click through to your previous or next post. This doesn’t work for random different posts.

#12: DNS prefetch external hostnames (Bonus!)

You can use something similar as the above prefetch & prerender code, to add hosts for DNS-prefetching:

<?php
function saotn_dns_prefetch() {
  echo '<meta http-equiv="x-dns-prefetch-control" content="on">
    <link rel="dns-prefetch" href="//secure.gravatar.com" />
    <link rel="dns-prefetch" href="//www.google-analytics.com" />
    <link rel="dns-prefetch" href="//apis.google.com" />
    <link rel="dns-prefetch" href="//ad.doubleclick.net" />
    <link rel="dns-prefetch" href="//pagead2.googlesyndication.com" />
    <link rel="dns-prefetch" href="//fonts.gstatic.com" />
    <link rel="dns-prefetch" href="//fonts.googleapis.com" />
    <link rel="dns-prefetch" href="//www.facebook.com" />
    <link rel="dns-prefetch" href="//scontent.xx.fbcdn.net" />
    <link rel="dns-prefetch" href="//gstatic.com" />
    <link rel="dns-prefetch" href="//cdnjs.cloudflare.com" />
    <link rel="dns-prefetch" href="//platform.twitter.com" />
    <link rel="dns-prefetch" href="//jetpack.wordpress.com" />
    <link rel="dns-prefetch" href="//s0.wp.com" />
    <link rel="dns-prefetch" href="//s1.wp.com" />
    <link rel="dns-prefetch" href="//s2.wp.com" />
    <link rel="dns-prefetch" href="//public-api.wordpress.com" />
    <link rel="dns-prefetch" href="//0.gravatar.com" />
    <link rel="dns-prefetch" href="//1.gravatar.com" />
    <link rel="dns-prefetch" href="//2.gravatar.com" />';
}
add_action( 'wp_head', 'saotn_dns_prefetch', 0 );

Only add hosts you really need prefetched.

WordPress resource hints (#13)

You can also make use of WordPress’ resource hints. Add the following to your site-specific plugin file to prefetch and prerender the previous and next post.

It also uses a dns-prefetch for maps.googleapis.com and use.typekit.net as example.

function change_to_preconnect_resource_hints( $hints, $relation_type ) {
	if ( 'prefetch' === $relation_type ) {
		$hints[] = get_permalink( $prev_post->ID );
	}
	if ( 'prerender' === $relation_type ) {
		$hints[] = get_permalink( $prev_post->ID );
	}
	if ( 'preconnect' === $relation_type ) {
		$hints[] = '//use.typekit.net';
		$hints[] = '//maps.googleapis.com';
	}

	if ( 'dns-prefetch' === $relation_type ) {
		$url_arr = array( 'maps.googleapis.com', 'use.typekit.net' );

		foreach ( $url_arr as $url ) {
			if ( ( $key = array_search( $url, $hints ) ) !== false ) {
				unset( $hints[ $key ] );
			}
		}
	}

	return $hints;
}
add_filter( 'wp_resource_hints', 'change_to_preconnect_resource_hints', 10, 2 );

#14: Switch from

By adding your own shortcode, in your site-specific plugin or theme functions.php file, you can easily create an shortcode to provide basic <?php function func_image( $atts, $content = null ) { return '<img src="' . $content . '"/>'; } add_shortcode( 'image', 'func_image' );

This creates the shortcode