When working on WordPress themes, it’s really useful to have a collection of code snippets in your code library to just copy and paste when a particular functionality needed. These code snippets can save your lots of time and speed up development. As we know that WordPress has a huge community which published tons of super handy code snippets and tips to help developers. Here in this post, I have compiled some of my favourite WordPress code snippets which surely extend functionality and save your precious time when developing WordPress themes.
All of these code snippets are simply cut-and-paste solutions for your theme’s functions.php file.
Display lightbox with all images embedded in a post
add_filter('the_content', 'add_lightbox'); function add_lightbox($content) { global $post; $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\") (.*?)>/i"; $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>'; $content = preg_replace($pattern, $replacement, $content); return $content; }
Get related posts by posts current author
function get_related_author_posts() { global $authordata, $post; $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post__not_in' => array( $post->ID ), 'posts_per_page' => 10 ) ); $output = '<ul>'; foreach ( $authors_posts as $authors_post ) { $output .= '<li><a href="' . get_permalink( $authors_post->ID ) . '">' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '< /a>< /li>'; } $output .= '< /ul>'; return $output; }
Get total number of images in media library
function get_image_count(){ $query_img_args = array( 'post_type' => 'attachment', 'post_mime_type' =>array( 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', ), 'post_status' => 'inherit', 'posts_per_page' => -1, ); $query_img = new WP_Query( $query_img_args ); echo $query_img->post_count; }
Restrict wp-admin access to subscribers
function restrict_access_admin_panel(){ global $current_user; get_currentuserinfo(); if ($current_user->user_level < 4) { wp_redirect( get_bloginfo('url') ); exit; } } add_action('admin_init', 'restrict_access_admin_panel', 1);
Increase the excerpt field height
add_action('admin_head', 'excerpt_textarea_height'); function excerpt_textarea_height() { echo' <style type="text/css"> #excerpt{ height:400px; } </style> '; }
Automatically add the Google +1 button
add_filter('the_content', 'add_google_plusone'); function add_google_plusone($content) { $content = $content.'
‘; return $content; } add_action (‘wp_enqueue_scripts’,’google_plusone_script’); function google_plusone_script() { wp_enqueue_script(‘google-plusone’, ‘https://apis.google.com/js/plusone.js’, array(), null); }
Limit search to specific post types
function limitPostSearch($query) { if ($query->is_search) { $query->set('post_type',array('post','page')); } return $query; } add_filter('pre_get_posts','limitPostSearch');
Automatically spam comments with a very long url
function check_spam( $approved , $commentdata ) { return ( strlen( $commentdata['comment_author_url'] ) > 50 ) ? 'spam' : $approved; } add_filter( 'pre_comment_approved', 'check_spam', 99, 2 );
Add custom text to WordPress login page
function add_login_message( $message ) { if ( empty($message) ){ return "<p class='message'>Welcome to this site. Please log in to continue</p>"; } else { return $message; } } add_filter( 'login_message', 'add_login_message' );
Force specific WordPress pages to be SSL secure
function force_page_ssl( $force_ssl, $post_id = 0, $url = '' ) { if ( $post_id == 25 ) { return true } return $force_ssl; } add_filter('force_ssl' , 'force_page_ssl', 10, 3);
Clean up wp_head() without a plugin
remove_action( 'wp_head', 'rsd_link' ); remove_action( 'wp_head', 'wlwmanifest_link' ); remove_action( 'wp_head', 'wp_generator' ); remove_action( 'wp_head', 'start_post_rel_link' ); remove_action( 'wp_head', 'index_rel_link' ); remove_action( 'wp_head', 'adjacent_posts_rel_link' ); remove_action( 'wp_head', 'wp_shortlink_wp_head' );
Automatically link Twitter usernames in WordPress
function twtreplace($content) { $twtreplace = preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/',"$1 <a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">@$2</a> ",$content); return $twtreplace; } add_filter('the_content', 'twtreplace'); add_filter('comment_text', 'twtreplace');
Redirect WordPress Feeds to Feedburner
add_action('template_redirect', 'rss_redirect'); function rss_redirect() { if ( is_feed() && !preg_match('/feedburner|feedvalidator/i' , $_SERVER['HTTP_USER_AGENT'])){ header('Location: http://feeds.feedburner.com/yourfeedname'); header('HTTP/1.1 302 Temporary Redirect'); } }
Email contributors when posts published
function email_notification($post_id) { $post = get_post($post_id); $author = get_userdata($post->post_author); $message = " Hi ".$author->display_name.", Your post, ".$post->post_title." has just been published. Well done! "; wp_mail($author->user_email, "Your article is online", $message); } add_action('publish_post', 'email_notification');
Add a Favicon
add_action( 'wp_head', 'add_favicon'); function add_favicon(){ echo " <link href="" . get_stylesheet_directory_uri() . "/favicon.ico" rel="shortcut icon" />" . "\n"; }
Shortcode to Display External Files
function show_external_file( $atts ) { extract( shortcode_atts( array( 'file' => '' ), $atts ) ); if ($file!='') return @file_get_contents($file); } add_shortcode( 'show_file', 'show_external_file' );
Create Custom Shortcodes
function show_message() { return 'Hi How Are You!'; } add_shortcode('message', 'show_message');
You can then use [message] wherever you want to display the content of the shortcode.
Add Content to the End of Each RSS Post
function feedFilter($query) { if ($query->is_feed) { add_filter('the_content','feedContentFilter'); } return $query; } add_filter('pre_get_posts','feedFilter'); function feedContentFilter($content) { $content .= 'Extra RSS content goes here... '; return $content; }
Detect which browser your visitors are using
add_filter('body_class','browser_body_class'); function browser_body_class($classes) { global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone; if($is_lynx) $classes[] = 'lynx'; elseif($is_gecko) $classes[] = 'gecko'; elseif($is_opera) $classes[] = 'opera'; elseif($is_NS4) $classes[] = 'ns4'; elseif($is_safari) $classes[] = 'safari'; elseif($is_chrome) $classes[] = 'chrome'; elseif($is_IE) $classes[] = 'ie'; else $classes[] = 'unknown'; if($is_iphone) $classes[] = 'iphone'; return $classes; }
Insert Author Bio for Each Post
function display_author_bio ($content=''){ global $post; $post_author_name=get_the_author_meta("display_name"); $post_author_description=get_the_author_meta("description"); $html="<div class='clearfix' id='about_author'>\n"; $html.="<img width='80' height='80' class='avatar' src='https://www.gravatar.com/avatar.php?gravatar_id=".md5(get_the_author_email()) . "&default=".urlencode($GLOBALS['defaultgravatar'])."&size=80&r=PG' alt='PG'/>\n"; $html.="<div class='author_text'>\n"; $html.="<h4>Author: ".$post_author_name."</h4>\n"; $html.= $post_author_description."\n"; $html.="</div>\n"; $html.="<div class='clear'></div>\n"; $content .= $html; } return $content; } add_filter('the_content', 'display_author_bio');