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