There are times when the plugins will not be helping you out in providing you the solution which you are looking for in actual at that time if you know or having some useful snippets – the short code – with you – then you can complete the task easily by adding the code in your theme’s file. With this article, I showcased twenty “must” WordPress snippets.
Add Contextual Help Tabs On Any Admin Page
The following snippet will let you create as many help tabs you would be requiring to switching the $screen_id.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
<?php function mqw_example_contextual_help( $contextual_help, $screen_id) { # Uncomment this to see actual screen # echo 'Screen ID = '.$screen_id.'<br />'; switch( $screen_id ) { case 'toplevel_page_settings_page' : // To add a whole tab group get_current_screen()->add_help_tab( array( 'id' => 'my-help-tab', 'title' => __( 'How to get started?' ), 'content' => __( 'Put any text here bla bla bla ....' ) ) ); break; case 'mi_plugin_page' : //Just to modify text of first tab $contextual_help .= '<p>'; $contextual_help = __( 'Your text here.' ); $contextual_help .= '</p>'; break; } return $contextual_help; } add_filter('contextual_help', 'mqw_example_contextual_help', 10, 2); ?> |
Source: WP-Snippets.
Add Custom Image Sizes To Media Insert Dialog
The following snippet will add new image sizes to the Upload/Insert dialog in WordPress. You need to add the code to your functions.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
<?php if ( function_exists( 'add_image_size' ) ) { add_image_size( 'new-size', 300, 100, true ); //(cropped) } add_filter('image_size_names_choose', 'my_image_sizes'); function my_image_sizes($sizes) { $addsizes = array( "new-size" => __( "New Size") ); $newsizes = array_merge($sizes, $addsizes); return $newsizes; } ?> |
Source: WP-Snippets
Author Bio Excerpt
The following code will let you show a short intro of the author of a post instead of his complete bio.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
<?php // Paste the code below to the functions.php file inside the theme directory you're using. function author_excerpt (){ $word_limit = 20; // Limit the number of words $more_txt = 'read more about:'; // The read more text $txt_end = '...'; // Display text end $authorName = get_the_author(); $authorUrl = get_author_posts_url( get_the_author_meta('ID')); $authorDescription = explode(" ", get_the_author_meta('description')); $displayAuthorPageLink = count($authorDescription) > $word_limit ? $txt_end.' '.$more_txt.' <a href="'.$authorUrl.'">'.$authorName.'</a>' : '' ; $authorDescriptionShort = array_slice($authorDescription, 0, ($word_limit)); return (implode($authorDescriptionShort, ' ')).$displayAuthorPageLink; } ?> <?php // Add this code snippet to the single.php file where you like to display the author bio excerpt. if (function_exists('author_excerpt')){echo author_excerpt();} ?> |
Automatically Set The Featured Image
The snippet will automatically set the featured image by fetching out the post’s first image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
<?php function autoset_featured() { global $post; $already_has_thumb = has_post_thumbnail($post->ID); if (!$already_has_thumb) { $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" ); if ($attached_image) { foreach ($attached_image as $attachment_id => $attachment) { set_post_thumbnail($post->ID, $attachment_id); } } } } add_action('the_post', 'autoset_featured'); add_action('save_post', 'autoset_featured'); add_action('draft_to_publish', 'autoset_featured'); add_action('new_to_publish', 'autoset_featured'); add_action('pending_to_publish', 'autoset_featured'); add_action('future_to_publish', 'autoset_featured'); ?> |
Check If Sidebar Has Widgets
The following snippet lets you check if a sidebar is having any widget areas into in it or not.
|
function is_sidebar_active($index) { global $wp_registered_sidebars; $widgetcolums = wp_get_sidebars_widgets(); if ($widgetcolums[$index]) return true; return false; } |
Check If The Visitor Is From Mobile Device
The snippet will let you see that whether your visitor is coming from mobile device or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
<?php // Add to functions.php // version proof, checks if the visitor is from a mobile device function muneeb_wp_is_mobile() { if ( function_exists( 'wp_is_mobile' ) ) return wp_is_mobile(); //code from wp_is_mobile function, wp_is_mobile() is located in wp-includes/vars.php version 3.4 static $is_mobile; if ( isset($is_mobile) ) return $is_mobile; if ( empty($_SERVER['HTTP_USER_AGENT']) ) { $is_mobile = false; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.) || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false ) { $is_mobile = true; } else { $is_mobile = false; } return $is_mobile; } // Use anywhere if ( muneeb_wp_is_mobile() ){ //do mobile stuff here } ?> |
Disable Plugin Updates
The snippet will disable on checking if there is any updates available for your plugins or not.
|
<?php remove_action( 'load-update-core.php', 'wp_update_plugins' ); add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) ); ?> |
Finding The First Link In Post
The snippet will let you find the first link in the post and then returns back to you. Using this will allow you to link the title to this place.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
function get_content_link( $content = false, $echo = false ) { if ( $content === false ) $content = get_the_content(); $content = preg_match_all( '/hrefs*=s*["']([^"']+)/', $content, $links ); $content = $links[1][0]; if ( empty($content) ) { $content = false; } return $content; } |
Force Direct Update
The snippet will allow you to force direct update for WordPress or plugins. All you have to do is to insert the code into wp-config.php file.
|
<?php define('FS_METHOD','direct'); ?> |
Hide Toolbar When There’s An Error
You need to add the snippet in your functions.php file letting you hide toolbar when there is an error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
<?php function wp_error($errno, $errstr, $errfile, $errline){ $errorType = array ( E_ERROR => 'ERROR', E_CORE_ERROR => 'CORE ERROR', E_COMPILE_ERROR => 'COMPILE ERROR', E_USER_ERROR => 'USER ERROR', E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR', E_WARNING => 'WARNING', E_CORE_WARNING => 'CORE WARNING', E_COMPILE_WARNING => 'COMPILE WARNING', E_USER_WARNING => 'USER WARNING', E_NOTICE => 'NOTICE', E_USER_NOTICE => 'USER NOTICE', E_DEPRECATED => 'DEPRECATED', E_USER_DEPRECATED => 'USER_DEPRECATED', E_PARSE => 'PARSING ERROR' ); if (array_key_exists($errno, $errorType)) { $errname = $errorType[$errno]; } else { $errname = 'UNKNOWN ERROR'; } echo $errname. ' Error: [' . $errno . '] ' . $errstr . $errfile . ' on line ' . $errline; remove_action( 'admin_footer', 'wp_admin_bar_render', 1000 ); } if(is_admin()){ set_error_handler('wp_error', E_ERROR ^ E_CORE_ERROR ^ E_COMPILE_ERROR ^ E_USER_ERROR ^ E_RECOVERABLE_ERROR ^ E_WARNING ^ E_CORE_WARNING ^ E_COMPILE_WARNING ^ E_USER_WARNING ^ E_NOTICE ^ E_USER_NOTICE ^ E_DEPRECATED ^ E_USER_DEPRECATED ^ E_PARSE ); } ?> |
Include All Post Types In Search
The snippet will let you include all post types in search.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
<?php function pippin_include_post_types_in_search($query) { if(is_search() && is_main_query()) { $post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects'); $searchable_types = array(); if($post_types) { foreach( $post_types as $type) { $searchable_types[] = $type->name; } } $query->set('post_type', $searchable_types); } return $query; } add_action('pre_get_posts', 'pippin_include_post_types_in_search'); ?> |
Override WordPress And Site URL
The snippet lets you override WordPress and site URL by redefining two constants which makes it possible for you to work with production databases.
|
<?php // Define wp home and site url define('WP_HOME','http://production.whateversite.com'); define('WP_SITEURL','http://production.whateversite.com'); ?> |
Source: WP-Snippet
QR code With Article Link
Using the following snippet will let you rendered QR-code for every article.
|
<img src="http://api.qrserver.com/v1/create-qr-code/?size=500x500&data=" <?php the_permalink() ?> " alt="QR Code for <?php the_title_attribute(); ?> "/> |
Redirect User After Login
The snippet will let you redirect user after login. Just add this code to your theme’s functions.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
<?php function redirect_user_on_role() { //retrieve current user info global $current_user; get_currentuserinfo(); //If login user role is Subscriber if ($current_user->user_level == 0) { wp_redirect( home_url() ); exit; } //If login user role is Contributor else if ($current_user->user_level > 1) { wp_redirect( home_url() ); exit; } //If login user role is Editor else if ($current_user->user_level >8) { wp_redirect( home_url() ); exit; } // For other rolse else { $redirect_to = 'http://google.com/'; return $redirect_to; } } add_action('admin_init','redirect_user_on_role'); ?> |
Remove Login Shake
Adding the snippet to functions.php file will let you remove the “wrong password” screen shake.
|
<?php function my_login_head() { remove_action('login_head', 'wp_shake_js', 12); } add_action('login_head', 'my_login_head'); ?> |
Remove WordPress Logo From Admin Bar
The following snippet will let you remove the WordPress logo on admin bar. You need to add the code to your functions.php file.
|
<?php function annointed_admin_bar_remove() { global $wp_admin_bar; /* Remove their stuff */ $wp_admin_bar->remove_menu('wp-logo'); } add_action('wp_before_admin_bar_render', 'annointed_admin_bar_remove', 0); ?> |
Set Featured Image Automatically
The following snippet will let you set featured image automatically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
<?php function set_featured_image_for_posts() { // Get all posts so set higher number, // you can increase to any number if you have big amount of posts $args = array( 'numberposts' => 5000); // all posts $all_posts = get_posts( $args ); foreach($all_posts as $k=>$v) { $args = array( 'numberposts' => 1, 'order'=> 'ASC', 'post_mime_type' => 'image', 'post_parent' => $v->ID, 'post_type' => 'attachment' ); // Get attachments $attachments = get_children( $args ); $i=0; foreach($attachments as $attach) { // Get only first image if($i==0) $attachmentsid = $attach->ID; $i++; } // Set Featured image set_post_thumbnail($v->ID,$attachmentsid); } } ?> |
Showing Admin Bar To Administrators
Add the code to your theme’s functions.php file to let you hide the admin bar to all logged in users except that of admins. A must for registrations-based sites.
|
<?php // Snippet code goes here! if (!current_user_can('administrator')) : show_admin_bar(false); endif; ?> |
Simple HTML In Widget Title
The snippet will allow you to easily use simple HTML tags in widget title area.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
<?php function html_widget_title( $title ) { //HTML tag opening/closing brackets $title = str_replace( '[', '<', $title ); $title = str_replace( '[/', '</', $title ); //<strong></strong> $title = str_replace( 's]', 'strong>', $title ); //<em></em> $title = str_replace( 'e]', 'em>', $title ); return $title; } add_filter( 'widget_title', 'html_widget_title' ); ?> |
Truncate Post Title
Add this snippet into your functions.php file and whenever you are in need of truncating a title, just call the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
<?php function customTitle($limit) { $title = get_the_title($post->ID); if(strlen($title) > $limit) { $title = substr($title, 0, $limit) . '...'; } echo $title; } ?> |
Source: WP-Snippets
Photo Credit: Flickr/Phil Oakley