17 Useful Code Snippets for WordPress Developers

17 Useful Code Snippets for WordPress Developers
by Janeth Kent Date: 09-08-2013 wordpress code snippets theme tips tricks code cms tutorials php

When coding WordPress themes, especially if you do it regularly, its really useful to have a selection of code snippets in your toolbox to just 'copy-n-paste' as and when the functionality needs. Not just your most commonly used code, but also some snippets that can, when required, extend WP even further.

In the collection below you can find 17 amazingly helpful code snippets which you can implement into your site. WordPress makes it super-easy to build off their own framework and classes. All of these codes are simply cut-and-paste solutions for your theme’s functions.php – which just goes to show WordPress’ creativity and novelty as a web CMS platform.

1. Increase the excerpt field height

add_action('admin_head', 'excerpt_textarea_height');  
function excerpt_textarea_height() {      
<style type="text/css">          
    #excerpt{ height:500px; }      

2. Dynamically create and attach sidebars to pages/posts

    $dynamic_widget_areas = array(  		
/* rename or create new dynamic sidebars */  		
"Sidebar 01",  		
"Sidebar 02",  		
"Sidebar 03",  		
"Sidebar 04",  		
"Sidebar 05",  		
"Sidebar 06",  		
"Sidebar 07",  		
"Search Template",  		
if ( function_exists('register_sidebar') ) {      
foreach ($dynamic_widget_areas as $widget_area_name) {          
'name'=> $widget_area_name,             
'before_widget' => '<div id="%1$s" class="widget %2$s left half">',             
'after_widget' => '</div>',            
 'before_title' => '<h3 class="widgettitle">',             
'after_title' => '</h3>',          
add_action("admin_init", "sidebar_init");  	
add_action('save_post', 'save_sidebar_link');  	

function sidebar_init(){  		
add_meta_box("sidebar_meta", "Sidebar Selection", "sidebar_link", "page", "side", "default");  	
function sidebar_link(){  		
global $post, $dynamic_widget_areas;  		
$custom  = get_post_custom($post->ID);  		
$link    = $custom["_sidebar"][0];  	
<div class="link_header">  	
<?  	echo '<select name="link" class="sidebar-selection">';  	
echo '<option>Select Sidebar</option>';  	
echo '<option>-----------------------</option>';  	
foreach ( $dynamic_widget_areas as $list ){  		    
if($link == $list){  		      
echo '<option value="'.$list.'" selected="true">'.$list.'</option>';  			
echo '<option value="'.$list.'">'.$list.'</option>';  			
echo '</select><br />';  	?>  
<p>Select sidebar to use on this page.</p> 
 <?php  }  
function save_sidebar_link(){  global $post;  
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {return $post->ID;}  	
update_post_meta($post->ID, "_sidebar", $_POST["link"]);  
add_action('admin_head', 'sidebar_css'); 
function sidebar_css() 
{  	echo'  	
<style type="text/css">  		
</style>  	';  

3. Remove the screen options tab with screen_options hook

function remove_screen_options(){      
return false;  
add_filter('screen_options_show_screen', 'remove_screen_options');

4. Display 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' => 5 ) );      
$output = '<ul>';      
foreach ( $authors_posts as $authors_post ) {          
$output .= '<li><a target="_blank" rel="nofollow"  href="' . get_permalink( $authors_post->ID ) . '">' . apply_filters( 'the_title', $authors_post->post_title, $authors_post->ID ) . '</a></li>';      }      
$output .= '</ul>';      
return $output;  }

5. Automatically add the Google +1 button

add_filter('the_content', 'google_plusone');  
function google_plusone($content) {  	
$content = $content.'<div class="plusone">
<g:plusone size="tall"target="_blank" rel="nofollow"  href="'.get_permalink().'"></g:plusone></div>';  	
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);  

6. Adjust settings on theme activation

add_action( 'after_setup_theme', 'the_theme_setup' );  
function the_theme_setup()  {  	
// First we check to see if our default theme settings have been applied.  	
$the_theme_status = get_option( 'theme_setup_status' );  	
// If the theme has not yet been used we want to run our default settings.  	
if ( $the_theme_status !== '1' ) {  		
// Setup Default WordPress settings  		
$core_settings = array(  			
'avatar_default'				=> 'mystery',					
// Comment Avatars should be using mystery by default  			
'avatar_rating'					=> 'G',							
// Avatar rating  			
'comment_max_links'				=> 0,							
// We do not allow links from comments  			
'comments_per_page'				=> 20							
// Default to 20 comments per page  		
foreach ( $core_settings as $k => $v ) {  			
update_option( $k, $v );  		
// Delete dummy post, page and comment.  		
wp_delete_post( 1, true );  		
wp_delete_post( 2, true );  		
wp_delete_comment( 1 );  		  		
update_option( 'theme_setup_status', '1' );  		
$msg = '  		<div class="error">  			
<p>The ' . get_option( 'current_theme' ) . 'theme has changed your WordPress default <a target="_blank" rel="nofollow"  href="' . admin_url() . 'options-general.php" title="See Settings">settings</a> and deleted default posts & comments.</p>  		
add_action( 'admin_notices', $c = create_function( '', 'echo "' . addcslashes( $msg, '"' ) . '";' ) 
}  	elseif ( $the_theme_status === '1' and isset( $_GET['activated'] ) ) {  		
$msg = '  		<div class="updated">  			<p>The ' . get_option( 'current_theme' ) . ' theme was successfully re-activated.</p>  		
add_action( 'admin_notices', $c = create_function( '', 'echo "' . addcslashes( $msg, '"' ) . '";' ) 

7. Count total number of images in media library

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

8. Display top 8 authors in wp_nav_menu using wp_list_authors

function wps_nav_authors($items, $args){      
if( $args->theme_location == 'header-navigation' )          
return $items . '<li><a target="_blank" rel="nofollow"  href="#">Authors</a><ul class="sub-menu"><li>' . wp_list_authors('show_fullname=1&optioncount=0&orderby=post_count&order=DESC&number=8&echo=0') . '</li></ul></li>';  
add_filter('wp_nav_menu_items','wps_nav_authors', 10, 2);

9. Get feedburner count using get_transient and wp_remote_get

function feed_subscribers(){          
$feed_url = 'http://feeds.feedburner.com/yourname';          
$count = get_transient('feed_count');          
if ($count != false) return $count;  	
$count = 0;          
$data  = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri='.$feed_url.'');
if (is_wp_error($data)) {          
return 'error';     }else{  	
$body = wp_remote_retrieve_body($data);  	
$xml = new SimpleXMLElement($body);  	
$status = $xml->attributes();  	
if ($status == 'ok') {  		
$count = $xml->feed->entry->attributes()->circulation;  	
} else {  		
$count = 300; // fallback number  	}     
set_transient('feed_count', $count, 60*60*24); // 24 hour cache  	
echo $count; 

10. Changing the HTML editor font in wp 3.2

add_action( 'admin_head-post.php', 'devpress_fix_html_editor_font' );  
add_action( 'admin_head-post-new.php', 'devpress_fix_html_editor_font' );  
function devpress_fix_html_editor_font() { ?>  
<style type="text/css">#editorcontainer #content, #wp_mce_fullscreen { font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; }</style>  
<?php } ?>

11. Restrict wp-admin access to subscribers

function restrict_access_admin_panel(){  	
global $current_user;  	
if ($current_user->user_level <  4) {  		
wp_redirect( get_bloginfo('url') );  		
exit;  	}  
add_action('admin_init', 'restrict_access_admin_panel', 1);

12. Add rel=”lightbox” to all images embedded in a post

add_filter('the_content', 'my_addlightboxrel');  function my_addlightboxrel($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; 

13. Change default “Enter title here” text within post title input field

function title_text_input( $title ){       
return $title = 'Enter new title';  
add_filter( 'enter_title_here', 'title_text_input'

14. Redirect commenter to thank you post or page

add_filter('comment_post_redirect', 'redirect_after_comment');  
function redirect_after_comment(){       

15. Create most recent posts dashboard widget

function wps_recent_posts_dw() {  ?>     <ol>       
global $post;            
$args = array( 'numberposts' => 5 );            
$myposts = get_posts( $args );  		
foreach( $myposts as $post ) :  
<li> (<? the_date('Y / n / d'); ?>) <a target="_blank" rel="nofollow"  href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endforeach; ?>     </ol>  
<?php  }  
function add_wps_recent_posts_dw() {         
wp_add_dashboard_widget( 'wps_recent_posts_dw', __( 'Recent Posts' ), 'wps_recent_posts_dw' );  }  
add_action('wp_dashboard_setup', 'add_wps_recent_posts_dw' );

16. Display hidden custom field _values

add_action( 'admin_head', 'showhiddencustomfields' );  
function showhiddencustomfields() {  	
echo "<style type='text/css'>#postcustom .hidden { display: table-row; }</style>\n";  

17. Loading jQuery from the Google CDN with wp_register_script

add_action( 'init', 'jquery_register' );  
function jquery_register() {  if ( !is_admin() ) {      
wp_deregister_script( 'jquery' );      
wp_register_script( 'jquery', ( 'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js' ), false, null, true );     
wp_enqueue_script( 'jquery' );     }  







by Janeth Kent Date: 09-08-2013 wordpress code snippets theme tips tricks code cms tutorials php hits : 6908  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.


Related Posts

Android Hidden Codes: unveiling custom dialer codes and their functionality

In the world of Android smartphones, there exist numerous hidden codes that can unlock a treasure trove of functionalities and features. These codes, known as custom dialer codes, provide access…

Secret iPhone codes to unlock hidden features

We love that our devices have hidden features. It's fun to learn something new about the technology we use every day, to discover those little features that aren't advertised by the…

Interesting and Helpful Google Search Features You’ll Want to Start Using

Google – THE search engine for many internet users. It has been with us since its launch back in 1998 and thanks to its simplicity of use and genius algorithms,…

How to use your browser as a file browser, in Chrome or Microsoft Edge

We're going to explain how to use the Chrome browser as a file browser, both on Android and on your computer. This is a hidden feature of Chromium that will…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java Approach: Selection Structures - Use Cases

Hello everyone and welcome back! Up to now we have been concerned to make as complete an overview as possible of the fundamental concepts we need to approach the use…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

How to watch deleted or private Youtube videos

Today we are going to talk about the technique which you permit to be able to recover videos from Youtube that was deleted, made private or simply blocked by Youtube…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

Data structures in Java - Linked Lists

With 2020 we are going to look at a new aspect of programming: data structures. It is often the case that everyone uses structures provided by the various programming languages.…

Introduction to REGEX - Regular Expression

Today we are going to write about Regular Expressions known as regex or shortened  regexp, a very useful concept of using search patterns. Surely you were in a situation when you…