17 Valuable WordPress snippets you never knew you could live without

Reading Time: 21 Minutes

17 valuable WordPress snippets for a site-specific plugin and functions.php that give 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 need for your WordPress site, to extend its speed & performance, functionality, security and user experience. Most of them are still good choices for your blog.

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.

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! :-)

Related:   WordPress CMS admin password reset

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.

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

#8: 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' );

#9: 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.

Related:   Install WordPress plugins without WP-admin access

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.

#10: 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.

#11: 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.

#12: Switch from [image] shortcode to HTML img tag easily #

This one may come in handy sometimes. Suppose you’ve switched WordPress themes, and your old theme provided an [image] shortcode. If you new theme doesn’t provide this shortcode, all your images are broken and the shortcode code is displayed. That ain’t pretty…

By adding your own shortcode, in your site-specific plugin or theme functions.php file, you can easily create an shortcode to provide basic [image] functionality: by returning an HTML img tag.

<?php
function func_image( $atts, $content = null ) {
  return '<img src="' . $content . '"/>';
}
add_shortcode( 'image', 'func_image' );

This creates the shortcode [image], and the $content (e.g your old image URL like “/path/to/image.png”) is put in between the shortcode. The returned img tag then fixes your old image shortcode, meaning you don’t have to manually edit tens or hundreds of posts. Like:

[image]//wp-content/uploads/2016/05/my-image.png[/image]

becomes:

<img src="//wp-content/uploads/2016/05/my-image.png"/>

But as always, this should be a short term solution until you’ve edited all your posts.

Related:   Quiet WordPress 4.7 RC2 available

#13: Google AdSense shortcode #

Add your AdSense code in a shortcode, to include Google AdSense anywhere in your WordPress posts (Source: Dutch article “Google AdSense advertenties in WordPress met shortcodes“)

<?php
function adsenseads_responsive() {
  $output = '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
    <!-- display my responsive Adsense ad  -->
    <ins class="adsbygoogle"
        style="display:block"
        data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
        data-ad-slot="xxxxxxxxxx"
        data-ad-format="auto"></ins>
    <script>
    (adsbygoogle = window.adsbygoogle || []).push({});
    </script>';
  return $output;
}
add_shortcode( 'showmyads_responsive', 'adsenseads_responsive' );

This adds the shortcode [showmyads_responsive] for easy usage in your posts.

#14: Change Akismet interval to delete spam comments #

Normally Akismet deletes spam comments after 15 days, which may be fine or may not. If you’d like to change, and shorten, the interval in which Akismet deletes spam comments, you can add the following code to your functions.php file:

<?php
add_filter( 'akismet_delete_comment_interval', 'custom_set_delete_interval' );
function custom_set_delete_interval() {
  return 3;
}

This sets Akismet delete comment interval to 3 days.

#15: WordPress optimization: Remove query strings from static resources, remove WordPress version number, and change stylesheet URL #

Three often heard WordPress optimization techniques are to

  1. remove query strings from static resources, making browsers able to cache the static files
  2. remove the WordPress version number, which adds some extra security -by obscurity, and
  3. change the stylesheet URL for content offloading

These snippets do just that.

<?php
function saotn_remove_query_strings( $src ) {
  if( strpos( $src, '?ver=' ) )
    $src = remove_query_arg( 'ver', $src );
    return $src;
  }
add_filter( 'style_loader_src', 'saotn_remove_query_strings', 10, 2 );
add_filter( 'script_loader_src', 'saotn_remove_query_strings', 10, 2 );
<?php
function saotn_remove_script_version( $src ){
  $parts = explode( '?ver', $src );
  return $parts[0];
}
add_filter( 'script_loader_src', 'saotn_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', 'saotn_remove_script_version', 15, 1 );
<?php
function saotn_remove_WP_version() {
  remove_action( 'wp_head', 'wp_generator' );
}
add_action( 'init', 'saotn_remove_WP_version' );
<?php
function saotn_stylesheet_directory_uri() {
  return "//cdn.example.com/wp-content/themes/[theme name]";
}
add_filter('stylesheet_directory_uri', 'saotn_stylesheet_directory_uri' );

Psst, want to make Twenty Seventeen full width?!

#16: Measure WordPress loading time and queries (Bonus!) #

Did you ever wanted to know how to measure WordPress’ loading time and executed database queries? During an HTTP request, WordPress executes a lot of queries on your MySQL database. Not only do these database queries take time, also the loading and execution of PHP takes time. It is important to measure this to be able to improve your WordPress loading speed.

But how does one measure this?

WordPress has built in functions to measure PHP’s loading time and executed MySQL queries. I’ve written a post on how to measure WordPress loading time and MySQL queries, using native WordPress functions. These functions are: get_num_queries() for the number of database queries, and timer_stop() for PHP execution time.

#17: Clear opcode caches before updating WordPress (Bonus!) #

Sometimes a WordPress update fails. Often this is due to installed opcode cache modules like OPcache, APC/APCu or WinCache. To streamline WordPress updates it’s handy to know how to flush this opcode cache before applying updates. My post clear PHP opcode caches before WordPress Updates: ease the updating process does just that.

Optimizing WordPress with code snippets, the conclusion #

Here you found some great WordPress functions.php (or site-specific plugin) code snippets. Snippets I use on a lot of my WordPress sites to optimize and enhance my WordPress sites. I hope you’ve found them useful.

Please share your code snippets you use in WordPress a lot through the comments, thanks!.

2 Replies to “17 Valuable WordPress snippets you never knew you could live without”

Hi! Join the discussion, leave a reply!