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() {      
echo'      
<style type="text/css">          
    #excerpt{ height:500px; }      
</style>     
 ';  
}

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' => '<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>';  			
}else{  		      
echo '<option value="'.$list.'">'.$list.'</option>';  			
}  		
}  	
echo '</select><br />';  	?>  
</div>  
<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">  		
  .sidebar-selection{width:100%;}  	
</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>  		
</div>';  		
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>  		
</div>';  		
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;  	
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 ="/<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(){       
wp_redirect('/thank-you-page/');        
exit();  
}

15. Create most recent posts dashboard widget

function wps_recent_posts_dw() {  ?>     <ol>       
<?php            
global $post;            
$args = array( 'numberposts' => 5 );            
$myposts = get_posts( $args );  		
foreach( $myposts as $post ) :  
setup_postdata($post); 
?>  		    
<li> (<? the_date('Y / n / d'); ?>) <a target="_blank" rel="nofollow"  href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>  	  
<?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 : 4617  
 
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 END DEVELOPMENT.

 
 
 

Related Posts

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…

A Java approach: variables

Hello everyone and welcome back! Today we will begin a journey that will lead us to study, and possibly review, what are the basics of programming. We will start by talking…

How to ‘leave’ a WhatsApp group without actually leaving

If you want to leave a WhatsApp group but don't want the 'You left the group' message to be displayed, read this article. Some people love WhatsApp groups, and some people…

The 6 Essentials for Creating a Visually Appealing Web Design

Creating a website might seem like a simple thing. After all, what do you really need besides a good hosting provider and relevant content, right? Well, the reality is quite…

How to get notified when one of your WhatsApp contact is online

Privacy is one of the most important aspects among most users of the popular Facebook messaging application. So much so, that many settings have been included in WhatsApp itself to…

How to change font size and format in WhatsApp

Your WhatsApp messages can be much more original and fun by changing the font, size, or format. Here's how. WhatsApp is the leading messaging app for virtually everyone, with permission from…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration