As this is my first post here on WP Daily I thought I best make it a good one!
I have been using WordPress for around 3 years now and have built up a pretty big code bank of little snippets and tricks to help me when I am building for WordPress. Over time I am going to share with you some of my most useful code snippets for use in your own projects or to build upon.
First I wanted to share with you what I think are my top 10 WordPress code snippets. These 10 snippets are used in nearly every single project I work on.
A quick note all these snippets are added to your functions.php file within your theme folder.
So lets begin…
1. Temporary Maintenance
This snippet I always place right at the top of my functions.php file. This will stop any users from seeing your website except logged in Administrators. Useful if you are doing some quick work that may cause the theme to break if something goes wrong.
[php]// Temp Maintenance – with http response 503 (Service Temporarily Unavailable)
// This will only block users who are NOT an administrator from viewing the website.
function wp_maintenance_mode(){
if(!current_user_can(‘edit_themes’) || !is_user_logged_in()){
wp_die(‘Maintenance, please come back soon.’, ‘Maintenance – please come back soon.’, array(‘response’ => ‘503’));
}
}
add_action(‘get_header’, ‘wp_maintenance_mode’);
[/php]
Once you have finished making your changes simply use PHP comments (//) to comment out the wp_die line eg.
[php]// wp_die(‘Maintenance, please come back soon.’, ‘Maintenance – please come back soon.’, array(‘response’ => ‘503’));[/php]
2. Custom Media Size Dropdown
This is a pretty cool function. Sometimes the default Medium and Large sizes when inserting an image into a post just isn’t enough range. Maybe you have a special size you use in posts but don’t want to change your Medium and Large file sizes just for that? Well this snippet will allow you to add another image size to the WordPress drop down menu, when inserting an image into a post.
[php]// Set the new image sizes
if(function_exists( ‘add_image_size’)){
add_image_size(‘blog-large’, 900, 700, false);
}
// Tell the media panel to add the new size to the dropbown
function custom_image_sizes($sizes) {
$addsizes = array(
"blog-large" => __("X-Large")
);
$newsizes = array_merge($sizes, $addsizes);
return $newsizes;
}
add_filter(‘image_size_names_choose’, ‘custom_image_sizes’);[/php]
To add more sizes just keep adding more add_image_size’s and add them to the $addsizes array.
3. Custom rel Tag In Galleries
Sometimes when your using a custom lightbox script with your theme you might have to add a rel tag to your links to allow the JavaScript to pick them up as a lightbox. This snippet looks complex but its simple to adapt just edit the rel tag to whatever your JavaScript needs for the lightbox to work.
[php]// Add rel tag to gallery images (Used for some Lightbox plugins / code)
function addlightboxrel_replace($content){
global $post;
$pattern = "/<a(.*?)href=(‘|")([^>]*).(bmp|gif|jpeg|jpg|png)(‘|")(.*?)>(.*?)</a>/i";
$replacement = ‘<a$1href=$2$3.$4$5 rel="gallery"$6>$7’;
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter(‘the_content’, ‘addlightboxrel_replace’, 12);
add_filter(‘get_comment_text’, ‘addlightboxrel_replace’);[/php]
4. Custom Failed Login Message
This snippet is good to add to every theme you create as it can help massively with your websites security.
What is does is overrides what WordPress outputs when the user log’s in incorrectly. As some of you may know when you get the password wrong for an account that exists WordPress will actually output a message saying the password for that account is wrong. Therefor telling the hacker that there is actually an account with that username to hack.
[php]// Change the failed login message for extra WordPress Secruty
function failed_login() {
return ‘Incorrect login information.’;
}
add_filter(‘login_errors’, ‘failed_login’);[/php]
5. Remove WordPress Version
Outdated WordPress installations can cause large security holes in your website and the longer you leave it the more chances there is of someone gaining access to your website. This small 4 lines of code will hide your current WordPress version to stop people finding out what version you are using. If they don’t know the version its harder to hack.
[php]// Remove the WP version for extra WordPress Secruty
function remove_wp_version(){
return ”;
}
add_filter(‘the_generator’, ‘remove_wp_version’);[/php]
6. Custom Class To Last Post In A Loop
This function I use all the time! You might need to change the margin or padding of your last post on a page to make it fit in with your theme. This function will add a class of ‘last’ to the very last post in a loop. Simple but effective.
[php]// Add a class to the last post in a loop
function last_post_class($classes){
global $wp_query;
if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = ‘last’;
return $classes;
}
add_filter(‘post_class’, ‘last_post_class’);[/php]
7. Anti Spam Email Links
We all know that mailto links are a target for even the most simple bots. However there are things we can do to try to protect the mailto link from the bots getting hold of your email account and before you know it filling your inbox with spam!
[php]
// Anti Spam Mailto Links
function email_encode_function($atts, $content){
return ‘<a href="’.antispambot($content).’">’.antispambot($content).'</a>’;
}
add_shortcode(’email’, ’email_encode_function’);
// Use shortcode [email][email protected][/email]
[/php]
To use this shortcode just add the following where you want the link to appear in your posts.
[code][email][email protected][/email][/code]
8. Hide WordPress Core Update Messages
This function should only really be used when you are managing a clients website for them and don’t want them updating something without your knowing.
It will simply hide the yellow bar that appears at the top when there is a new version released.
[php]// Hide WordPress Update
function wp_hide_update() {
remove_action(‘admin_notices’, ‘update_nag’, 3);
}
add_action(‘admin_menu’,’wp_hide_update’);[/php]
9. Snapshot Of Any Website
A nice little function that uses a shortcode to output a real-time thumbnail of any website you specify.
[php]// Output a snapshot of any website!
function wp_snap($atts, $content = NULL) {
extract(shortcode_atts(array(
"snap" => ‘http://s.wordpress.com/mshots/v1/’,
"url" => ‘https://torquemag.io/’,
"alt" => ‘WPDaily’,
"w" => ‘400’, // width
"h" => ‘300’ // height
), $atts));
$img = ‘<img alt="’ . $alt . ‘" src="’ . $snap . ” . urlencode($url) . ‘?w=’ . $w . ‘&h=’ . $h . ‘" />’;
return $img;
}
add_shortcode("snap", "wp_snap");
// Use [snap url="https://torquemag.io/" alt="WPDaily Website" w="400" h="300"][/php]
To use this shortcode just add the following to your post.
[code][snap url="https://torquemag.io/" alt="WPDaily Website" w="400" h="300"][/code]
10. Admin Only Notes
This is a small feature however I and my clients find it useful when multiple users manage the same website.
Add the shortcode “[note]This will appear only to admins[/note]” to any post to display a message on the website that will only appear to logged in administrators. Useful for editing notes and change requests.
[php]// Admin Note
function adminnote($atts, $content = NULL){
if(current_user_can(‘edit_themes’) || is_user_logged_in()){
return ‘</pre>
<div style="margin-bottom: 22px; font-family: Consolas, Monaco, ‘Courier New’, Courier, monospace; font-size: 12px; font-weight: inherit; overflow-x: auto; white-space: -o-pre-wrap; width: 99%; word-wrap: break-word; background: #f3f3f7; border: 1px solid #dedee3; padding: 11px; line-height: 1.3em;"><b>Admin Notice</b>
‘ . $content . ‘</div>
<pre>
‘;
}
}
add_shortcode(‘note’, ‘adminnote’);
// Use [note]This will appear only to admins[/note][/php]
So there you have it my top 10 WordPress code snippets and my first ever post here on WP Daily!
If you have any of your own code snippets please share them in the comments below and let me know what you think of my top 10 snippets I’d love your feedback!
WordPress Codex Reference Links
34 Comments