17 Useful Code Snippets for WordPress Developers

17 Useful Code Snippets for WordPress Developers

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() {      
echo'      
     
 ';  
}

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) {          
register_sidebar(array(             
'name'=> $widget_area_name,             
'before_widget' => '
', 'after_widget' => '
', 'before_title' => '

', 'after_title' => '

', )); } } 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]; ?>

Select sidebar to use on this page.

ID;} update_post_meta($post->ID, "_sidebar", $_POST["link"]); } add_action('admin_head', 'sidebar_css'); function sidebar_css() { echo' '; }

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 = '';      
return $output;  }

5. Automatically add the Google +1 button

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

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 = '  		

The ' . get_option( 'current_theme' ) . 'theme has changed your WordPress default settings and deleted default posts & comments.

'; add_action( 'admin_notices', $c = create_function( '', 'echo "' . addcslashes( $msg, '"' ) . '";' ) ); } elseif ( $the_theme_status === '1' and isset( $_GET['activated'] ) ) { $msg = '

The ' . get_option( 'current_theme' ) . ' theme was successfully re-activated.

'; 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 . '
  • Authors
  • '; } 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() { ?>  
      
    
    

    11. 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);
    

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

    add_filter('the_content', 'my_addlightboxrel');  function my_addlightboxrel($content) {         
    global $post;         
    $pattern ="//i";         
    $replacement = '';         
    $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(){       
    wp_redirect('/thank-you-page/');        
    exit();  
    }

    15. Create most recent posts dashboard widget

    function wps_recent_posts_dw() {  ?>     
      5 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?>
    1. ()

    16. Display hidden custom field _values

    add_action( 'admin_head', 'showhiddencustomfields' );  
    function showhiddencustomfields() {  	
    echo "\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' );     }  
    }