Sysadmins of the North
Share now!





17+ Useful WordPress snippets

Here are 17+ valuable WordPress snippets for site-specific plugins and functions.php to provide 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! (-:

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

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(); for that matter) 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.

Add a WhatsApp button on Social Share Buttons – #2

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;
}

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

Load Facebook Like Box Asynchronously (async) – #3

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:   Install WordPress plugins without WP-admin access

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;
  	::$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> 
	'; 
}

Did you spot js.async = true;? 🙂

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

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

<?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 );

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

So you want to prettify your fonts, and Enfold may be lacking some fonts? 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;
}

Remove PHP Sessions in Enfold – #7

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 primarily 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 WordPress SEO?), 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.

Load default WordPress jQuery from Google Library – #8

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 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 (false is the default value), to load jQuery in your HTML header.

Remove jQuery Migrate – #9

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.

So here’s a small 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' );

Clean expired transients autmatically – #10

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:   Exploit PHP's mail() to get remote code execution

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.

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

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

If defined, they’ll tell your browser to start loading the given URL to render 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.

DNS prefetch external hostnames (Bonus!) – #12

You can use something similar as the above prefetch & prerender, 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 );

Switch from shortcode to HTML img tags easily – #14

This one may come in handy sometimes. Suppose you’ve switched WordPress themes, and your old theme provided an shortcode. If your new theme doesn’t provide this same 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 functionality: by returning an HTML &lt;img tag.

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

This creates the shortcode for your site, and the $content (e.g your old image URL like “/path/to/image.png”) is put in between the shortcode. The returned <img src="" tag fixes your old theme image shortcode, meaning you don’t have to manually edit tens or hundreds of posts.

This may interest you:   Set WP_MEMORY_LIMIT value correctly in wp-config.php

For example the shortcode in posts:

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.

Google AdSense shortcode – tip #15

Add your AdSense ad-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 for easy usage in your posts.

Change Akismet interval to delete spam comments – #16

Normally Akismet deletes spam comments after 15 days, which may be fine with you or 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’s delete comment interval to 3 days.

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

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

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

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

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

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


buy me a coffee
Buy Me A Coffee

About the Author Jan Reilink

My name is Jan. I am not a hacker, coder, developer, programmer or guru. I am merely a system administrator, doing my daily thing at Vevida in the Netherlands. With over 15 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, WordPress, websites & optimization. Want to support me and donate? Use this link: https://paypal.me/jreilink.

follow me on:


Thank you!

Leave a Comment:

1 comment
Add Your Reply
Skip to content