Shun the Plugin: 100 WordPress Code Snippets from Across the Net
A few weeks back it was thank a plugin developer day. I love those guys. They make me happy. But I love them so much that I end up filling my website with plugins to achieve things that I could achieve with code.
Nowadays I love code snippets. They’re handy, like a million times handy. They’re useful for developers and for people who want to customize their themes. Want to do something with WordPress and don’t know how? Just search for a snippet – someone will usually have done it already.
But what if you had 100 useful WordPress code snippets in one place? It’d be great, right? Surely no one could be bothered posting 100 snippets on a blog. That would take forever!
Yes, it did take forever.
Some Words of Warning
Basics
Branding
Dashboard
Navigation
Widgets
Analytics
Text Editor
Users
Search
Posts
Lists of Posts
Category
Comments
Authors
Security
Social Media & Sharing
Child Themes
Media
Traffic
Advertising
Multisite
Misc
Some Words of Warning
ALWAYS back up your site before making any changes to the code. You could end up with something as innocuous as too many spaces or you might come up against plugin compatibility. Even if you are 100% sure of something it is always worth taking precautions.
Leland has some good advice for theme developers who are using code snippets in their themes. / If you have two functions with the same name in your theme then it’s not going to work and you’re going to spend hours trying to figure out what the problem is. If you’re planning on using any of these snippets in themes or plugins that you’re going to create and release then you should consider renaming the functions to something individual to prevent problems later. You don’t want to end up with a whole bunch of angry emails. You’ll notice that some of the functions already have very distinctive names. You can read Andrew Nacin’s blog for more on this.
Basics
1. Increase Memory Limit
If you’ve got a lot of plugins or a lot of traffic you may need to increase your memory limit. You need to add this to your wp-config file:
define(‘WP_MEMORY_LIMIT’, ’96M’);
Source: WP Snippets
2. Empty Trash Automatically
Does what it says – set the number of days and reduce the size of your database.
define(‘EMPTY_TRASH_DAYS’, 5 );
Source: Tutzone
3. Filter the Loop
Filter which posts you want to show. This snippet is only showing “Featured.”
query_posts(‘showposts=5&category_name=featured’);
if ( have_posts() ) : while ( have_posts() ) : the_post();
<h3><a href=«<?php the_permalink(); ?>«><?php the_title(); ?></a></h3>
<p><?php the_content(); ?></p>
endwhile; else:
endif;
wp_reset_query();
Source: WP Snippets
4. Loop the loop
Or… add a loop within the loop, but loop the loop sounds much cooler.
if (have_posts()) :
while (have_posts()) : the_post(); // the post loop
$temp_query = $wp_query; // store it
$args = array(
‘paged’ => $paged, // paginates
‘post_type’=>‘post’,
‘posts_per_page’ => 3,
‘order’ => ‘DESC’
);
$wp_query = new WP_Query($args);
while ($wp_query—>have_posts()) : $wp_query—>the_post();
// — your new loop — //
>endwhile;
if (isset($wp_query)) {$wp_query = $temp_query;} // restore loop
>endwhile;
endif;
Source: WP Snippets
5. Detect Browser
If you want to use a different stylesheet for different browsers you can use HTML conditional tags or you can use this.
add_filter(‘body_class’,‘browser_body_class’);
function browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = ‘lynx’;
elseif($is_gecko) $classes[] = ‘gecko’;
elseif($is_opera) $classes[] = ‘opera’;
elseif($is_NS4) $classes[] = ‘ns4’;
elseif($is_safari) $classes[] = ‘safari’;
elseif($is_chrome) $classes[] = ‘chrome’;
elseif($is_IE) $classes[] = ‘ie’;
else $classes[] = ‘unknown’;
if($is_iphone) $classes[] = ‘iphone’;
return $classes;
}
Source: Lava 360
6. Detect Mobile Users
If you want to serve up something special to your mobile visitors you can use this snippet to find out when they have arrived on your website. To achieve this you have to visit detectmobilebrowsers.mobi and upload it to your theme directory. Place at the top of your header file. Make sure you edit line 5 of this to your own theme.
include(‘mobile_device_detect.php’);
$mobile = mobile_device_detect();
if ($mobile==true) {
header( ‘Location: http://your-website.com/?theme=Your_Mobile_Theme’ ) ;
}
Source: WP Recipes
7. Leverage Browser Caching using .htaccess
This is a great snippet for speeding up your website. Paste it into .htaccess (remember to backup!)
## EXPIRES CACHING ##
ExpiresActive On
ExpiresByType image/jpg «access 1 year»
ExpiresByType image/jpeg «access 1 year»
ExpiresByType image/gif «access 1 year»
ExpiresByType image/png «access 1 year»
ExpiresByType text/css «access 1 month»
ExpiresByType application/pdf «access 1 month»
ExpiresByType text/x-javascript «access 1 month»
ExpiresByType application/x-shockwave-flash «access 1 month»
ExpiresByType image/x-icon «access 1 year»
ExpiresDefault «access 2 days»
## EXPIRES CACHING ##
Source: Thomas Griffin
8. Include jQuery the right way
WordPress already includes a copy of jQuery so there is actually no need to upload it on to your server. It must be above the wp_head function
<?php wp_enqueue_script(«jquery»); ?>
You can now call your script after the wp_head function.
Source: Digging into WordPress
9. Switch on Maintenance Mode
Need a quick maintenance mode? Use this snippet. Just comment it out when you don’t want it switched on.
function maintenace_mode() {
if ( !current_user_can( ‘edit_themes’ ) || !is_user_logged_in() ) {
die(‘Maintenance.’);
}
}
add_action(‘get_header’, ‘maintenace_mode’);
Source: WP Snippets
10. Simpler Login Address
Find the default login address too cumbersome? You can change this by editing your .htaccess. Before to back it up before tinkering. Add this before the default WordPress code:
RewriteRule ^login$ http://yoursite.com/wp-login.php [NC,L]
Source: Digging into WordPress
11. Remove WordPress 3.1 Admin Bar
It’s not been released yet but WordPress 3.1 comes with an admin bar a la WordPress.com. Here’s how to remove it:
remove_action(‘init’, ‘wp_admin_bar_init’);
Source: WP Recipes
12. Limit Post Revisions
I love the autosave function but I do end up with loads of post revisions. Use this to limit the number.
# Maximum 5 revisions #
define(‘WP_POST_REVISIONS’, 5);
# Disable revisions #
define(‘WP_POST_REVISIONS’, false);
Source: Lava 360
13. Set Autosave time
WordPress’ autosave is very handy. This snippet lets you specify how often it happens. Copy to your wp-config.php
# Autosave interval set to 5 Minutes #
define(‘AUTOSAVE_INTERVAL’, 300);
Source: WP Zine
Branding
14. Customize WordPress Login Logo Without a Plugin
This is great for people building websites for clients who want to have their own branding all over the installation.
function my_custom_login_logo() {
echo ‘<style type=«text/css»>
h1 a { background-image:url(‘.get_bloginfo(‘template_directory’).‘/images/custom-login-logo.gif) !important; }
</style>‘;
}
add_action(‘login_head’, ‘my_custom_login_logo’);
Source: WP Recipes
15. Change Admin Logo
Don’t just change your login logo, change your admin logo as well. Make sure you add your admin_logo.png to your images folder.
function custom_admin_logo() {
echo ‘<style type=«text/css»>
#header-logo { background-image: url(‘.get_bloginfo(‘template_directory’).‘/images/admin_logo.png) !important; }
</style>‘;
}
add_action(‘admin_head’, ‘custom_admin_logo’);
Source: WP Snippets
16. Change Footer Text in WP Admin
This goes nicely with the change of logo. Change the footer text to anything you like:
function remove_footer_admin () {
echo ‘Siobhan is Awesome. Thank you <a href=«http://wordpress.org»>WordPress</a> for giving me this filter.’;
}
add_filter(‘admin_footer_text’, ‘remove_footer_admin’);
Source: Lava360
17. Dynamic Copyright Date in Footer
Your footer should display your copyright something along the lines of 2005 – 2011. Usually people only have the current year, or they have some time in the past because they haven’t updated it. Use this snippet to make the date dynamic so you don’t have to worry about it every again.
function comicpress_copyright() {
global $wpdb;
$copyright_dates = $wpdb—>get_results(»
SELECT
YEAR(min(post_date_gmt)) AS firstdate,
YEAR(max(post_date_gmt)) AS lastdate
FROM
$wpdb—>posts
WHERE
post_status = ‘publish’
«);
$output = »;
if($copyright_dates) {
$copyright = «© « . $copyright_dates[0]—>firstdate;
if($copyright_dates[0]—>firstdate != $copyright_dates[0]—>lastdate) {
$copyright .= ‘-‘ . $copyright_dates[0]—>lastdate;
}
$output = $copyright;
}
return $output;
}
Then insert this into your footer:
<?php echo comicpress_copyright(); ?>
Source: WP Beginner
18.Add Favicon
Everyone loves a favicon. They’re so cute! Use this in your functions.php to add one:
<span style=«font-weight: normal;»> </span>
// add a favicon to your
function blog_favicon() {
echo ‘<link rel=«Shortcut Icon» type=«image/x-icon» href=«‘.get_bloginfo(‘wpurl’).‘/favicon.ico» />‘;
}
add_action(‘wp_head’, ‘blog_favicon’);
Source: WP Beginner
19. Add Custom Background
This is a nice and simple way to register a custom background.
// Add support for backgrounds
add_custom_background();
Source: DJAvupixel.com
Dashboard
20. Remove Menus in WordPress Dashboard
Clients confused about why they have a menu section for “posts”? Do they end up creating posts instead of pages and then call you up asking you why their page isn’t showing? Happened to all of us…. Remove menus in the WordPress dashboard:
function remove_menus () {
global $menu;
$restricted = array(__(‘Dashboard’), __(‘Posts’), __(‘Media’), __(‘Links’), __(‘Pages’), __(‘Appearance’), __(‘Tools’), __(‘Users’), __(‘Settings’), __(‘Comments’), __(‘Plugins’));
end ($menu);
while (prev($menu)){
$value = explode(‘ ‘,$menu[key($menu)][0]);
if(in_array($value[0] != NULL?$value[0]:«» , $restricted)){unset($menu[key($menu)]);}
}
}
add_action(‘admin_menu’, ‘remove_menus’);
Source: WPRecipes
21. Remove sub menus from admin panel
You can also remove sub menus. You can find the sub menu names in wp-admin/menu.php
function remove_submenus() {
global $submenu;
unset($submenu[‘index.php’][10]); // Removes ‘Updates’.
unset($submenu[‘themes.php’][5]); // Removes ‘Themes’.
unset($submenu[‘options-general.php’][15]); // Removes ‘Writing’.
unset($submenu[‘options-general.php’][25]); // Removes ‘Discussion’.
}
add_action(‘admin_menu’, ‘remove_submenus’);
Source: WP Snippets
22. Add Custom Dashboard Widgets
Want additional dashboard widgets to give some info to your clients? Use this snippet:
add_action(‘wp_dashboard_setup’, ‘my_custom_dashboard_widgets’);
function my_custom_dashboard_widgets() {
global $wp_meta_boxes;
wp_add_dashboard_widget(‘custom_help_widget’, ‘Theme Support’, ‘custom_dashboard_help’);
}
function custom_dashboard_help() {
echo ‘<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href=«mailto:yourusername@gmail.com»>here</a>. For WordPress Tutorials visit: <a href=«http://www.wpbeginner.com» target=«_blank»>WPBeginner</a></p>‘;
}
Source: WP Beginner
23. Hide update message
If you don’t want clients to be able to update WordPress themselves you could use this piece of code to hide the nag message.
add_action(‘admin_menu’,‘wphidenag’);
function wphidenag() {
remove_action( ‘admin_notices’, ‘update_nag’, 3 );
}
Source: WP Beginner
24. Edit the Help dropdown
This could come in handy if you are creating websites for clients and you want to add extra contextual help.
//hook loading of new page and edit page screens
add_action(‘load-page-new.php’,‘add_custom_help_page’);
add_action(‘load-page.php’,‘add_custom_help_page’);
function add_custom_help_page() {
//the contextual help filter
add_filter(‘contextual_help’,‘custom_page_help’);
}
function custom_page_help($help) {
//keep the existing help copy
echo $help;
//add some new copy
echo «<h5>Custom Features</h5>«;
echo «<p>Content placed above the more divider will appear in column 1. Content placed below the divider will appear in column 2.</p>«;
}
Source: Smashing Magazine
25. WordPress Relative Date
Instead of displaying the date that your post was posted, you can make it relative – “6 months ago” or “3 weeks ago” or whatever. Use this in your posts/comments/pages
# For posts & pages #
<?php echo human_time_diff(get_the_time(‘U’), current_time(‘timestamp’)) . ‘ ago’;
# For comments #
<?php echo human_time_diff(get_comment_time(‘U’), current_time(‘timestamp’)) . ‘ ago’; ?>
Source: WP Snippets
Navigation
26. Automatically Add a Search Box to Your Nav Menu
Want to automatically add a search box to your nav? Here’s how:
add_filter(‘wp_nav_menu_items’,‘add_search_box’, 10, 2);
function add_search_box($items, $args) {
ob_start();
get_search_form();
$searchform = ob_get_contents();
ob_end_clean();
$items .= ‘<li>‘ . $searchform . ‘</li>‘;
return $items;
}
Source: WP Recipes
27. Remove Title from WordPress Menu Links
The title attributes for your menu links can disrupt any jQuery that you’re using for a dropdown. Use this to remove it.
function my_menu_notitle( $menu ){
return $menu = preg_replace(‘/ title=«(.*?)«/’, », $menu );
}
add_filter( ‘wp_nav_menu’, ‘my_menu_notitle’ );
add_filter( ‘wp_page_menu’, ‘my_menu_notitle’ );
add_filter( ‘wp_list_categories’, ‘my_menu_notitle’ );
Source: Dynamic WP
28. Edit Navigation Output
Want more control over the navigation output? This is a great snippet for it. Place this in your functions.php file and edit the PHP for the results you want.
class description_walker extends Walker_Nav_Menu
{
function start_el(&amp;amp;amp;amp;amp;amp;amp;amp;amp;$output, $item, $depth, $args)
{
global $wp_query;
$indent = ( $depth ) ? str_repeat( «t», $depth ) : »;
$class_names = $value = »;
$classes = empty( $item—>classes ) ? array() : (array) $item—>classes;
$class_names = join( ‘ ‘, apply_filters( ‘nav_menu_css_class’, array_filter( $classes ), $item ) );
$class_names = » : ‘«‘;
$output .= $indent . ‘
<li id=«menu-item-‘. $item—>ID . ‘«‘ . $value . $class_names .‘>‘;
$attributes = ! empty( $item—>attr_title ) ? ‘ title=»‘ . esc_attr( $item—>attr_title ) .‘«‘ : »;
$attributes .= ! empty( $item—>target ) ? ‘ target=«‘ . esc_attr( $item—>target ) .‘«‘ : »;
$attributes .= ! empty( $item—>xfn ) ? ‘ rel=»‘ . esc_attr( $item—>xfn ) .‘«‘ : »;
$attributes .= ! empty( $item—>url ) ? ‘ href=»‘ . esc_attr( $item—>url ) .‘«‘ : »;
if($depth != 0)
{
$description = $append = $prepend = ««;
}
$item_output = $args—>before;
$item_output .= ‘<a’ . $attributes . ‘>‘;
$item_output .= $args—>link_before .$prepend.apply_filters( ‘the_title’, $item—>title, $item—>ID ).$append;
$item_output .= $description.$args—>link_after;
$item_output .= ‘</a>‘;
$item_output .= $args—>after;
$output .= apply_filters( ‘walker_nav_menu_start_el’, $item_output, $item, $depth, $args );
}
}
Source: Lava 360
29. Breadcrumbs without a plugin
Create those breadcrumb trails without the help of a plugin. Insert this into functions.php
function the_breadcrumb() {
echo ‘<ul id=«crumbs»>‘;
if (!is_home()) {
echo ‘<li><a href=«‘;
echo get_option(‘home’);
echo ‘»>‘;
echo ‘Home’;
echo «</a></li>«;
if (is_category() || is_single()) {
echo ‘<li>‘;
the_category(‘ </li><li> ‘);
if (is_single()) {
echo «</li><li>«;
the_title();
echo ‘</li>‘;
}
} elseif (is_page()) {
echo ‘<li>‘;
echo the_title();
echo ‘</li>‘;
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo«<li>Archive for «; the_time(‘F jS, Y’); echo‘</li>‘;}
elseif (is_month()) {echo«<li>Archive for «; the_time(‘F, Y’); echo‘</li>‘;}
elseif (is_year()) {echo«<li>Archive for «; the_time(‘Y’); echo‘</li>‘;}
elseif (is_author()) {echo«<li>Author Archive»; echo‘</li>‘;}
elseif (isset($_GET[‘paged’]) && !empty($_GET[‘paged’])) {echo «<li>Blog Archives»; echo‘</li>‘;}
elseif (is_search()) {echo«<li>Search Results»; echo‘</li>‘;}
echo ‘</ul>‘;
}
Insert into header.php
<?php the_breadcrumb(); ?>
Source: WP Snippets
30. Pagination
Want pagination at the bottom of your blog? Insert this into your functions.php
function my_paginate_links() {
global $wp_rewrite, $wp_query;
$wp_query—>query_vars[‘paged’] > 1 ? $current = $wp_query—>query_vars[‘paged’] : $current = 1;
$pagination = array(
‘base’ => @add_query_arg(‘paged’,‘%#%’),
‘format’ => »,
‘total’ => $wp_query—>max_num_pages,
‘current’ => $current,
‘prev_text’ => __(‘« Previous’),
‘next_text’ => __(‘Next »’),
‘end_size’ => 1,
‘mid_size’ => 2,
‘show_all’ => true,
‘type’ => ‘list’
);
if ( $wp_rewrite—>using_permalinks() )
$pagination[‘base’] = user_trailingslashit( trailingslashit( remove_query_arg( ‘s’, get_pagenum_link( 1 ) ) ) . ‘page/%#%/’, ‘paged’ );
if ( !empty( $wp_query—>query_vars[‘s’] ) )
$pagination[‘add_args’] = array( ‘s’ => get_query_var( ‘s’ ) );
echo paginate_links( $pagination );
}
Use CSS to style it how you want.
Source: WPEngineer
Widgets
31. Disable standard widgets
If you want to keep widgets out of client’s hands you can use this snippet:
function unregister_default_wp_widgets() {
unregister_widget(‘WP_Widget_Calendar’);
unregister_widget(‘WP_Widget_Search’);
unregister_widget(‘WP_Widget_Recent_Comments’);
}
add_action(‘widgets_init’, ‘unregister_default_wp_widgets’, 1);
Source: WP Snippets
32. Add Shortcodes to Widgets
Want to add shortcodes to widgets? We all do. Here’s how:
add_filter(‘widget_text’, ‘do_shortcode’)
Source: WP Snippets
Analytics
33. Google Analytics Without Editing Theme
Ever update your parent theme and then realise a few weeks later that you haven’t added your Google Analytics tracking code? All those stats, lost! Add your tracking code to your functions instead:
<?php
add_action(‘wp_footer’, ‘ga’);
function ga() { ?>
// Paste your Google Analytics code here
<?php } ?>
Source: LG Creative
Text Editor
34. Set the Default Text Editor
Don’t like the default WYSIWYG editor? Change it the default to the HTML editor using functions.php
# This sets the Visual Editor as >default #
add_filter( ‘wp_default_editor’, create_function(», ‘return «tinymce»;‘) );
# This sets the HTML Editor as >default #
add_filter( ‘wp_default_editor’, create_function(», ‘return «html»;‘) );
Source: WP Snippets
35. Change the HTML Editor Font
Can’t stand courier? Use this to change your font. Paste into your functions.php
function change_editor_font(){
echo «<style type=‘text/css’>
#editorcontainer textarea#content {
font-family: Monaco, Consolas, «Andale Mono«, «Dejavu Sans Mono«, monospace;
font-size:14px;
color:#333;
}
</style>«;
} add_action(«admin_print_styles», «change_editor_font»);
Source: WP Recipes
36. Style the Visual Editor
You can style the visual editor. Simply create your new CSS file – something like editor-style.css and then include the following snippet in your functions
function change_editor_font(){
echo «<style type=‘text/css’>
#editorcontainer textarea#content {
font-family: Monaco, Consolas, «Andale Mono«, «Dejavu Sans Mono«, monospace;
font-size:14px;
color:#333;
}
</style>«;
} add_action(«admin_print_styles», «change_editor_font»);
Source: Andrew Ozz
37. Change the Spell Check Language
By default the language of the spell checker in English. You can change it with the following snippet (which allows English and German)
function fb_mce_external_languages($initArray){
$initArray[‘spellchecker_languages’] = ‘+German=de, English=en’;
return $initArray;
}
add_filter(‘tiny_mce_before_init’, ‘fb_mce_external_languages’);
Source: WP Engineer
Users
38. Add Custom User Contact Info
WordPress, for some reason, still asks you to fill in your AIM and Yahoo IM. I don’t know about you but I haven’t logged into Yahoo IM for about 3 years, and AIM since before 2000. User this snippet to change it to the social media you actually use.
/* BEGIN Custom User Contact Info */
function extra_contact_info($contactmethods) {
unset($contactmethods[‘aim’]);
unset($contactmethods[‘yim’]);
unset($contactmethods[‘jabber’]);
$contactmethods[‘facebook’] = ‘Facebook’;
$contactmethods[‘twitter’] = ‘Twitter’;
$contactmethods[‘linkedin’] = ‘LinkedIn’;
return $contactmethods;
}
add_filter(‘user_contactmethods’, ‘extra_contact_info’);
/* END Custom User Contact Info */
Then use this code wherever you want to display it:
<a href=«<?php the_author_meta(‘facebook’, $current_author—>ID); ?>«></a>
Source: Thomas Griffin
Search
39. Highlight search terms
This is a nice one. Power up your search functionality by highlighting the search term in the results.
Open search.php and find the the_title() function
Replace with:
echo $title;
Above the modified line add:
<?php
<span style=«white-space: pre;«> </span>$title <span style=«white-space: pre;«> </span>= get_the_title();
<span style=«white-space: pre;«> </span>$keys= explode(» «,$s);
<span style=«white-space: pre;«> </span>$title <span style=«white-space: pre;«> </span>= preg_replace(‘/(‘.implode(‘|‘, $keys) .‘)/iu’,
<span style=«white-space: pre;«> </span>‘<strong class=«search-excerpt»>0</strong>‘,
<span style=«white-space: pre;«> </span>$title);
?>
Add the following to your style.css. Add:
strong.search-excerpt { background: yellow; }
Source: WP Recipes
40. Exclude Posts and Pages from Search Results
Sometimes you don’t want all of your posts and pages appearing in your search results. Use this snippet to shun whichever ones you want.
// search filter
function fb_search_filter($query) {
if ( !$query—>is_admin && $query—>is_search) {
$query—>set(‘post__not_in’, array(40, 9) ); // id of page or post
}
return $query;
}
add_filter( ‘pre_get_posts’, ‘fb_search_filter’ );
To exclude the subpage of a page you need to add it to the IS:
// search filter
function fb_search_filter($query) {
if ( !$query—>is_admin && $query—>is_search) {
$pages = array(2, 40, 9); // id of page or post
// find children to id
>foreach( $pages as $page ) {
$childrens = get_pages( array(‘child_of’ => $page, ‘echo’ => 0) );
}
// add id to array
>for($i = 0; $i < sizeof($childrens); ++$i) { $pages[] = $childrens[$i]—>ID;
}
$query—>set(‘post__not_in’, $pages );
}
return $query;
}
add_filter( ‘pre_get_posts’, ‘fb_search_filter’ );
Source: WPEngineer
41. Disable WordPress Search
There may be sites that you have where you don’t want users to be able to search. Use this snippet to remove the search functionality.
function fb_filter_query( $query, $error = true ) {
if ( is_search() ) {
$query—>is_search = false;
$query—>query_vars[s] = false;
$query—>query[s] = false;
// to error
>if ( $error == true )
$query—>is_404 = true;
}
}
add_action( ‘parse_query’, ‘fb_filter_query’ );
add_filter( ‘get_search_form’, create_function( ‘$a’, «return null;» ) );
Source: WP Engineer
Posts
42. Set a Maximum Word Count on Post Titles
Manage a blog with multiple users? Use this snippet to set a maximum word count on your titles.
function maxWord($title){
global $post;
$title = $post—>post_title;
if (str_word_count($title) >= 10 ) //set this to the maximum number of words
wp_die( __(‘Error: your post title is over the maximum word count.’) );
}
add_action(‘publish_post’, ‘maxWord’);
Source: WP Recipes
43. Set Minimum Word Count on Posts
Make those pesky authors write more:
function minWord($content){
global $post;
$num = 100; //set this to the minimum number of words
$content = $post—>post_content;
if (str_word_count($content) < $num) wp_die( __(‘Error: your post is below the minimum word count.’) ); } add_action(‘publish_post’, ‘minWord’);
Source: WP Recipes
44. Add Default Text to your Posts
This snippet will let you add default text that appears in every new post.
<?php
add_filter( ‘default_content’, ‘my_editor_content’ );
function my_editor_content( $content ) {
$content = «This is some custom content I’m adding to the post editor because I hate re-typing it.»;
return $content;
}
?>
Source: Justin Tadlock
45. Add Custom Content Under Each Post
You may want to add a custom piece of content under each post – perhaps a copyright notice, some advertising or you could just say “thanks for reading!”
function add_post_content($content) {
if(!is_feed() && !is_home()) {
$content .= ‘<p>This article is copyright © ‘.date(‘Y’).‘ ‘.bloginfo(‘name’).‘</p>‘;
}
return $content;
}
add_filter(‘the_content’, ‘add_post_content’);
Source: WP Recipes
46. Display Incremental Numbers Next to Each Published Post
This snippet lets you add numbers beside your posts. You could use Article 1, Article 2, Article 3; or Post 1, Post 2, Post 3; or whatever you want.
Add this to your functions:
function updateNumbers() {
global $wpdb;
$querystr = «SELECT $wpdb—>posts.* FROM $wpdb—>posts WHERE $wpdb—>posts.post_status = ‘publish’ AND $wpdb—>posts.post_type = ‘post’ «;
$pageposts = $wpdb—>get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
$counts++;
add_post_meta($post—>ID, ‘incr_number’, $counts, true);
update_post_meta($post—>ID, ‘incr_number’, $counts);
endforeach;
endif;
}
add_action ( ‘publish_post’, ‘updateNumbers’ );
add_action ( ‘deleted_post’, ‘updateNumbers’ );
add_action ( ‘edit_post’, ‘updateNumbers’ );
Then add this within the loop:
<?php echo get_post_meta($post—>ID,‘incr_number’,true); ?>
Source: WP Recipes
47. Shorten the excerpt
Think the excerpt is too long? Use this snippet to shorten it. This shortens it to 20 words.
function new_excerpt_length($length) {
return 20;
}
add_filter(‘excerpt_length’, ‘new_excerpt_length’);
Source: Lava360
Lists of Posts
48. Display Random Posts
Shows a nice list of some random posts. Stop your long lost posts from being forgotten. Paste this wherever you want it.
<ul><li><h2>A random selection of my writing</h2>
<ul>
<?php
$rand_posts = get_posts(‘numberposts=5&amp;amp;amp;amp;amp;amp;amp;amp;amp;orderby=rand’);
foreach( $rand_posts as $post ) :
?>
<li><a href=«<?php the_permalink(); ?>«><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
</li></ul>
Source: Lava 360
49. Display Most Popular Post from a Specific Category
Sometimes you might want to display only your popular posts from your “Featured” category, or your “books” category. Use this snippet to achieve it.
<?php
$args=array(
‘cat’ => 3,
‘orderby’ => ‘comment_count’,
‘order’ => ‘DESC’,
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => 6,
‘caller_get_posts’=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query—>have_posts() ) { ?>
<ul>
<?php while ($my_query—>have_posts()) : $my_query—>the_post(); ?>
<li><a href=«<?php the_permalink() ?>« rel=«bookmark» title=«Permanent Link to <?php the_title_attribute(); ?>«><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php }
wp_reset_query(); ?>
Remember to change this line to the category you want:
‘cat’ => 3,
And set this line to how many posts you want to display:
‘posts_per_page’ => 6,
Source: Dynamic WP
50. List Upcoming Posts
Want to tantalize your readers with what you’ve got to come? What to display an event that’s happening in the future? This snippet will let you list which posts you have in draft.
<div id=«zukunft»>
<div id=«zukunft_header»><p>Future events</p></div>
<?php query_posts(‘showposts=10&post_status=future’); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div >
<p class><b><?php the_title(); ?></b><?php edit_post_link(‘e’,‘ (‘,‘)‘); ?><br />
<span><?php the_time(‘j. F Y’); ?></span></p>
</div>
<?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?>
</div>
Source: WP Recipes
51. Show Related Posts
It’s nice to be able to show your related posts – and without a plugin it’s even better.
<?php
$tags = wp_get_post_tags($post—>ID);
if ($tags) {
echo ‘Related Posts’;
$first_tag = $tags[0]—>term_id;
$args=array(
‘tag__in’ => array($first_tag),
‘post__not_in’ => array($post—>ID),
‘showposts’=>1,
‘caller_get_posts’=>1
);
$my_query = new WP_Query($args);
if( $my_query—>have_posts() ) {
while ($my_query—>have_posts()) : $my_query—>the_post(); ?>
<p><a href=«<?php the_permalink() ?>« rel=«bookmark» title=«Permanent Link to <?php the_title_attribute(); ?>«><?php the_title(); ?></a></p>
<?php
endwhile; wp_reset();
}
}
?>
Source: Snipp.it
52. Popular Posts Based on Comment Count
It’s nice to be able to list all of your most popular posts based on the number of comments.
<h2>Popular Posts</h2>
<ul>
<?php $result = $wpdb->get_results(«SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 10»);
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>
<li><a href=«<?php echo get_permalink($postid); ?>« title=«<?php echo $title ?>«>
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>
</ul>
Source: LG Creative
53. Display Latest Posts
Easily show your latest posts
<?php query_posts(‘showposts=5‘); ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li><a href=«<?php the_permalink() ?>«><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>
Source: Web Designer Wall
Pages
54. Custom Page Style
Page templates are great for differentiating different types of pages. You can use this snippet. Just drop it into a new PHP file and upload it. You’ll be able to access it by using the page template dropdown menu when creating a page.
/* Template name: Custom Page Name */
/* Describe the custom page here! */
get_header();
# The loop n’ all! #
the_sidebar();
get_footer();
Source: Lava 360
Custom Post Types
55. Create Custom Post Type
Everyone’s favourite.
$args = array(
‘label’ => __(‘Products’),
‘singular_label’ => __(‘Product’),
‘public’ => true,
‘show_ui’ => true,
‘capability_type’ => ‘page’,
‘hierarchical’ => false,
‘rewrite’ => true,
‘query_var’ => ‘products’,
‘supports’ => array(‘title’, ‘thumbnail’)
);
register_post_type( ‘product’ , $args );
Source: Cats Who Code
56. Different RSS Feed for Each Custom Post Type/Taxonomy
This sounds like something which should be incredibly difficult. Actually, it’s not. All you have to do is append the custom post type to the URL:
http://www.yoursite.com/feed/?post_type=book
Then you can add a custom taxonomy to it too.
http://www.yoursite.com/feed/?post_type=book&genre=romance
Source: WPBeginner
57. Editor Styles for Custom Post Types
Want to use different stylesheets for each of your custom post types? You can use this snippet. Make sure to insert your own custom post type names and your own stylesheet names.
function my_editor_style() {
global $current_screen;
switch ($current_screen—>post_type) {
case ‘post’:
add_editor_style(‘editor-style-post.css’);
break;
case ‘page’:
add_editor_style(‘editor-style-page.css’);
break;
case ‘portfolio’:
add_editor_style(‘editor-style-portfolio.css’);
break;
}
}
add_action( ‘admin_head’, ‘my_editor_style’ );
Source: WP Storm
Category
58. Order Category by Most Recently Updated
This is a nice piece of code for ordering your categories.
<?php
$cat_array = array();
$args=array(
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => 20,
‘caller_get_posts’=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query—>have_posts() ) {
while ($my_query—>have_posts()) : $my_query—>the_post();
$cat_args=array(‘orderby’ => ‘none’);
$cats = wp_get_post_terms( $post—>ID , ‘category’, $cat_args);
foreach($cats as $cat) {
$cat_array[$cat—>term_id] = $cat—>term_id;
}
endwhile;
}
if ($cat_array) {
foreach($cat_array as $cat) {
$category = get_term_by(‘ID’,$cat, ‘category’);
echo ‘<a href=«‘ . esc_attr(get_term_link($category, ‘category’)) . ‘» title=»‘ . sprintf( __( «View all posts in %s» ), $category—>name ) . ‘» ‘ . ‘>‘ . $category—>name.‘</a>‘.‘<br />‘;
}
}
wp_reset_query();
?>
Source: Dynamic WP
59. Exclude Specific Category
It can sometimes come in handy to exclude specific categories from being displayed.
<?php query_posts(‘cat=—2‘); ?>
<?php while (have_posts()) : the_post(); ?>
//the loop here
<?php endwhile;?>
Source: Web Designer Wall
Comments
60. Display Recent Comments with Gravatar
This is a nice way to achieve something simple without the use of a plugin. You can show off your latest comments in your sidebar, with the gravatar. Just paste this into your sidebar.php
<?php $comments = get_comments(‘status=approve&number=5‘); ?>
<ul>
<?php foreach ($comments as $comment) { ?>
<li>
<?php echo get_avatar( $comment, ’35’ ); ?>
<a href=«<?php echo get_permalink($comment—>ID); ?>#comment-<?php echo $comment—>comment_ID; ?>« title=«on <?php echo $comment—>post_title; ?>«> <?php echo strip_tags($comment—>comment_author); ?>: <?php echo wp_html_excerpt( $comment—>comment_content, 35 ); ?>… </a>
</li>
<?php } ?>
</ul>
Source: Dynamic WP
61. Display Number of Comments
If you want a quick way to show off your number of comments you can add this to your sidebar.php
<?php
$commcount = $wpdb—>get_var(«SELECT COUNT(*) FROM $wpdb—>comments WHERE comment_approved = ‘1‘«);
if (0 < $commcount) $commcount = number_format($commcount);
echo «Our users have made «.$commcount.» comments, care to join in?«;
?>
Source: PHP Magicbook
62. Style Comments for Every Role
This lets you style the comments for different roles.
<ol id=«commentlist»>
<?php foreach ($comments as $comment) : ?>
<?php // The extra stuff to get commenter‘s role
$user_id = $comment—>user_id;
$role = ( isset( $roles[$user_id] ) ? $roles[$user_id] : ‘‘ );
?>
<li>
<p>By <?php comment_author_link() ?> — <?php comment_date() ?></p>
<?php comment_text() ?>
</li>
<?php endforeach; ?>
</ol>
Add this to your style.css
#commentlist li { border:2px solid white; } /* not logged or subscriber */
#commentlist li.administrator { border:2px solid red } /* blog admin */
#commentlist li.editor { border:2px solid blue } /* editor */
Source: Design Beginner
63. Add “Del” and “Spam” buttons to your comments
It can be a bit of a pain having to go to the admin area just to spam some piece of junk. You can use this snippet to add the “Del” and “Spam” buttons to your comments on the front end.
Add this to functions.php
function delete_comment_link($id) {
if (current_user_can(‘edit_post’)) {
echo ‘| <a href=«‘.admin_url(«comment.php?action=cdc&c=$id«).‘»>del</a> ‘;
echo ‘| <a href=»‘.admin_url(«comment.php?action=cdc&dt=spam&c=$id«).‘»>spam</a>‘;
}
}
Add the following after edit_comment_link()
delete_comment_link(get_comment_ID());
Source: WP Recipes
64. Remove Autolinks in Comments
Spammers love to leave links in your comments. Stop those urls from turning into links.
remove_filter(‘comment_text’, ‘make_clickable’, 9);
Source: WP Recipes
65. Disable HTML in Comments
This is very useful if you have lots of people posting pieces of code in your comments. No longer will it disappear!
// This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {
// convert everything in a comment to display literally
$incoming_comment[‘comment_content’] = htmlspecialchars($incoming_comment[‘comment_content’]);
// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
$incoming_comment[‘comment_content’] = str_replace( «‘», »’, $incoming_comment[‘comment_content’] );
return( $incoming_comment );
}
// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {
// Put the single quotes back in
$comment_to_display = str_replace( »’, «‘«, $comment_to_display );
return $comment_to_display;
}
add_filter( ‘preprocess_comment’, ‘plc_comment_post’, », 1);
add_filter( ‘comment_text’, ‘plc_comment_display’, », 1);
add_filter( ‘comment_text_rss’, ‘plc_comment_display’, », 1);
add_filter( ‘comment_excerpt’, ‘plc_comment_display’, », 1);
Source: Peter’s Useless Crap
66. Separate Trackbacks from Comments
Trackbacks are great for acknowledging people who have linked to you and they help you to keep track of where your post has appeared. However, they can be annoying when they break up your comments. Use this snippet to separate them.
Find this in your comments.php
foreach ($comments as $comment) : ?>
// Comments are displayed here
endforeach;
And replace with this:
<ul class=«commentlist»>
<?php //Displays comments only
<span style=«white-space: pre;«> </span>foreach ($comments as $comment) : ?>
<span style=«white-space: pre;«> </span><?php $comment_type = get_comment_type(); ?>
<span style=«white-space: pre;«> </span><?php if($comment_type == ‘comment’) { ?>
<span style=«white-space: pre;«> </span> <li>//Comment code goes here</li>
<span style=«white-space: pre;«> </span><?php }
endforeach;
</ul>
<ul>
<?php //Displays trackbacks only
<span style=«white-space: pre;«> </span>foreach ($comments as $comment) : ?>
<span style=«white-space: pre;«> </span><?php $comment_type = get_comment_type(); ?>
<span style=«white-space: pre;«> </span><?php if($comment_type != ‘comment’) { ?>
<span style=«white-space: pre;«> </span> <li><?php comment_author_link() ?></li>
<span style=«white-space: pre;«> </span><?php }
endforeach;
</ul>
Source: WP Recipes
Authors
67. Change Name to Guest Author
Often guest authors will post one time only. You don’t want to set up an account for them so you post under your own name. You can use this snippet along with custom fields to change the post author name to the guest author. Add this to your functions:
add_filter( ‘the_author’, ‘guest_author_name’ );
add_filter( ‘get_the_author_display_name’, ‘guest_author_name’ );
function guest_author_name( $name ) {
global $post;
$author = get_post_meta( $post—>ID, ‘guest-author’, true );
if ( $author )
$name = $author;
return $name;
}
Then add a custom field called guest-author and put the author’s name into the value.
Source: WP Beginner
68. Insert Author Box
Give your hardworking blog authors the credit they deserve. To insert an author box beneath a post insert this into your single.php after the article tags:
<div>
<div>
<div><?php echo get_avatar( get_the_author_email(), ’80’ ); ?></div>
</div>
<div>
<div><?php the_author_meta( «display_name» ); ?></div>
<div><?php the_author_meta( «user_description» ); ?></div>
<div><?php if (get_the_author_url()) { ?><a href=«<?php the_author_url(); ?>«>Visit <?php the_author(); ?>‘s website</a><?php } else { } ?></div>
</div>
<div></div>
</div>
And here’s some CSS to make it pretty.
.author-box { padding: 10px; background: #ccc; border: 1px solid #333;}
.author-left {float:left; width: 80px; margin: 0 15px 0 0;}
.author-right {float:left; font-size: 13px; margin: 5px 0 0 10px;}
.author-pic {border: 1px solid: #ccc;}
.author-name {font-weight:bold;}
.author-bio {padding: 5px 0 5px 0;}
.author-url {color: #555;}
.author-url a {color: #000;}
.author-url a:hover {color: #333;}
.clear {clear:both}
Source: WP Zine
69. Highlight Post Author Comments
This one is very useful for sites with multiple authors. The snippet only highlights the post author, as opposed to all of the authors on the site.
Insert this into your CSS file:
.commentlist .bypostauthor {
/* — Add a darker border — */
border: 1px #bbb solid;
/* — CSS3 Linear Gradient — */
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#f5f5f5), to(#ddd));
background: -moz-linear-gradient(0% 100% 90deg,#ddd, #f5f5f5);
/* — CSS3 Shadow — */
-webkit-box-shadow:0px 0 50px #ddd;
-moz-box-shadow:0px 0 50px #ddd;
box-shadow:0px 0 50px #ddd;
}
Source: Voosh Themes
Security
70. Force Users to Log in Before Reading a Post
If there are certain posts that you want to restrict, whether they for a few people only, or for paying subscribers, or whatever, you can use this snippet to force users to login to see them. Paste this into your functions file:
function my_force_login() {
global $post;
if (!is_single()) return;
$ids = array(188, 185, 171); // array of post IDs that force login to read
if (in_array((int)$post—>ID, $ids) && !is_user_logged_in()) {
auth_redirect();
}
}
And then put this at the top of your header:
<?php my_force_login(); ?>
Source: WP Beginner
71. Force SSL usage
If you’re concerned about your admin being accessed you could force SSL usage. You’ll need to make sure you can do this with your hosting.
define(‘FORCE_SSL_ADMIN’, true);
Source: Smashing Magazine
72. Change the default admin name
It’s a good idea to not have a username called “admin” as it means that any hackers already have access to your username. If you already have a default called “admin” you can change it with this snippet in your SQL database. Make sure to put in your new username.
UPDATE wp_users SET user_login = ‘Your New Username’ WHERE user_login = ‘Admin’;
Source: Smashing Magazine
73. Protect your wp-config.php
Use this snippet to protect the precious. Add this to your .htaccess file
<Files wp-config.php>
order allow,deny
deny from all
</Files>
Source: WP Zine
74. Remove the WordPress version
This is especially helpful if you’re using an older version of WordPress. Best not tell anyone else that you are.
function no_generator() { return »; }
add_filter( ‘the_generator’, ‘no_generator’ );
Source: WP Zine
75. Only allow your own IP address to access your admin
If you’ve got a static IP and you want to improve your security this is a good snippet. Don’t bother if you have a dynamic IP though. It would get very annoying.
# my ip address only
order deny,allow
allow from MY IP ADDRESS (replace with your IP address)
deny from all
Source: WP Zine
76. Prevent Access to WP-Admin
This code snippet is handy for preventing subscribers from having access to /wp-admin/. You can change the wp_user_level to whichever roles you want.
# Disable access to wp-admin for Subscribers
if ( is_user_logged_in() && is_admin() ) {
global $current_user;
get_currentuserinfo();
$user_info = get_userdata($current_user—>ID);
if ( $user_info—>wp_user_level == 0 )
{
header( ‘Location: ‘.get_bloginfo(‘home’).‘/wp-login.php?redirect=‘.get_bloginfo(‘home’).‘/wp-admin/’ );
}
}
Source: Flowdrops
Social Media & Sharing
77. Share Via Email
Let everyone share your work. They can click on the button which opens the visitor’s default email client. Then they can email people and tell them how much they love you.
<?php echo «<a href=»mailto:type%20email%20address%20here?subject=I%20wanted%20to
%20share%20this%20post%20with%20you%20from%20
<?php bloginfo(‘name’); ?>&amp;amp;amp;amp;amp;amp;amp;amp;amp;body=<?php the_title(); ?> — <?php the_permalink(); ?>»
title=«Email to a friend/colleague»target=«_blank»>Share via Email</a>«; ?>
Source: Lava 360
78. Add Facebook and Twitter to the bottom of each post
Easily add Facebook and Twitter to the bottom of your posts by adding this to your functions.php
function share_this($content){
if(!is_feed() && !is_home()) {
$content .= ‘<div class=«share-this»>
<a href=«http://twitter.com/share»
class=«twitter-share-button»
data-count=«horizontal»>Tweet</a>
<script type=«text/javascript»
src=«http://platform.twitter.com/widgets.js»></script>
<div class=«facebook-share-button»>
<iframe
src=«http://www.facebook.com/plugins/like.php?href=’.
urlencode(get_permalink($post—>ID))
.‘&layout=button_count&show_faces=false&width=200&action=like&colorscheme=light&height=21″
scrolling=«no» frameborder=«0« style=«border:none;
overflow:hidden; width:200px; height:21px;«
allowTransparency=«true»></iframe>
</div>
</div>‘;
}
return $content;
}
add_action(‘the_content’, ‘share_this’);
Source: WP Recipes
79. Display Feedburner Counter
Proud of all your subscribers on Feedburner? Show them off to the world. Remember to change the feedburner address to your own.
<?php
$url = file_get_contents(‘https://feedburner.google.com/api/awareness/1.0/Get
FeedData?uri=YOUR FEED ADDRESS’);
$begin = ‘circulation=«‘; $end = ‘»‘;
$page = $url;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$fbcount = $parts[0];
if($fbcount == ») { $fbcount = ‘0‘; }
echo ‘<b> ‘.$fbcount.‘ </b> Subscribers’;
?>
Source: webm.ag
80. Display your number of Twitter Followers
You can add your Twitter followers too! Make sure you insert your own username.
<?php
$twit = file_get_contents(‘http://twitter.com/users/show/USERNAME.xml’);
$begin = ‘<followers_count>‘; $end = ‘</followers_count>‘;
$page = $twit;
$parts = explode($begin,$page);
$page = $parts[1];
$parts = explode($end,$page);
$tcount = $parts[0];
if($tcount == ») { $tcount = ‘0‘; }
echo ‘<b> ‘.$tcount.‘ </b> Followers’;
?>
Source: webm.ag
81. Display Your Facebook Fans
You don’t want your Facebook fans to feel left out. Use this snippet to show them off too – replace YOUR-PAGE-ID with your page ID.
<?php
$page_id = «YOUR PAGE-ID»;
$xml = @simplexml_load_file(«http://api.facebook.com/restserver.php?method=facebook.fql.query&amp;amp;amp;amp;amp;amp;amp;amp;amp;query=SELECT%20fan_count%20FROM%20page%20WHERE%
20page_id=«.$page_id.«») or die («a lot»);
$fans = $xml—>page—>fan_count;
echo $fans;
?>
Source: Lava 360
82. Use Tweetmeme
You can use this snippet to show your visitors how hot you are on Twitter.
<script type=«text/javascript»>// <![CDATA[
tweetmeme_style = ‘compact’; tweetmeme_service = ‘bit.ly’; tweetmeme_source = ‘twitterusername’; tweetmeme_url = »
// ]]></script>
<script src=«http://tweetmeme.com/i/scripts/button.js» type=«text/javascript»></script>
<script type=«text/javascript»>
tweetmeme_style = ‘compact’;
tweetmeme_service = ‘bit.ly’;
tweetmeme_source = ‘twitterusername’;
tweetmeme_url = ‘<?php the_permalink() ?>‘
</script>
<script type=«text/javascript» src=«http://tweetmeme.com/i/scripts/button.js»></script>
Source: Nenuno
Child Themes
83. Remove Unnecessary Widget Regions
Additional widget regions can get confusing for people if they aren’t using them. If you’re building a child theme for a client it’s a good idea to remove additional widget areas.
Here’s what the code looks like to register widgets in a theme framework:
//Code of the Framework to register 2 Sidebars
function xtreme_register_dynamic_sidebars() {
register_sidebar( array(
‘name’ => ‘Sidebar One’,
‘id’ => ‘sidebar-one’,
‘description’ => ‘Sidebar One’,
‘before_widget’ => ‘<li id=«%1$s» class=«widget %2$s»>‘,
‘after_widget’ => ‘</li>‘,
‘before_title’ => ‘<h5 class=«widget-title»>‘,
‘after_title’ => ‘</h5>‘
));
register_sidebar( array(
‘name’ => ‘Sidebar Two’,
‘id’ => ‘sidebar-two’,
‘description’ => ‘Sidebar Two’,
‘before_widget’ => ‘ <li id=«%1$s» class=«widget %2$s»>‘,
‘after_widget’ => ‘</li>‘,
‘before_title’ => ‘<h5 class=«widget-title»>‘,
‘after_title’ => ‘</h5>‘
));
do_action(‘childtheme_sidebars’);
}
add_action( ‘widgets_init’, ‘xtreme_register_dynamic_sidebars’ );
What we’re interested in is do_action(‘childtheme_sidebars’);
Add this to your child theme’s functions.php
//functions.php im Child-Theme
function xtreme_unregister_sidebar() {
unregister_sidebar(‘sidebar-two’);
}
add_action( ‘childtheme_sidebars’, ‘xtreme_unregister_sidebar’ );
Source: WP Engineer
84. Unregister sidebar
This can be used in a parent or child but it’s particularly helpful for child themes where the parent has more sidebars than you need.
<?php
// This is amazingly helpful for child themes.
function remove_sidebar() {
<span style=«white-space: pre;«> </span>unregister_sidebar(‘SIDEBAR_ID’);
}
add_action( ‘admin_init’, ‘remove_sidebar’);
?>
Source: CodeSnipp.it
Media
85. Automatically use Resized Images instead of originals
Replace your uploaded image with the large image generated by WordPress. This will save space on your server, and save bandwidth if you link your thumbnail to the original image. I love things that speed up your website.
function replace_uploaded_image($image_data) {
// if there is no large image : return
if (!isset($image_data[‘sizes’][‘large’])) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir[‘basedir’] . ‘/’ .$image_data[‘file’];
$large_image_location = $upload_dir[‘path’] . ‘/’.$image_data[‘sizes’][‘large’][‘file’];
// delete the uploaded image
unlink($uploaded_image_location);
// rename the large image
rename($large_image_location,$uploaded_image_location);
// update image metadata and return them
$image_data[‘width’] = $image_data[‘sizes’][‘large’][‘width’];
$image_data[‘height’] = $image_data[‘sizes’][‘large’][‘height’];
unset($image_data[‘sizes’][‘large’]);
return $image_data;
}
add_filter(‘wp_generate_attachment_metadata’,‘replace_uploaded_image’);
Source: WP Recipes
Traffic
86. Detect User from Yahoo
Freak your visitors out by saying “Hello! Yahoo User.”
<?php if (strpos($_SERVER[HTTP_REFERER], «yahoo») ) {
echo «Hello Yahoo! User!«;
} ?>
Source: WP Snippets
87. Detect User from Google
Do the same from Google.
if (strpos($_SERVER[HTTP_REFERER], «google») == true) {
echo «Hello Google User!«;
}
Source: WP Snippets
88. Detect Twitter User
And from Twitter
if (strpos($_SERVER[HTTP_REFERER], «twitter.com») == true) {
echo «Hello Twitter User!«;
}
Source: WP Snippets
89. Display Search Terms from Google users
Paste this anywhere outside the header to display all the search terms your visitors will have used to find your site.
<?php
$refer = $_SERVER[«HTTP_REFERER»];
if (strpos($refer, «google»)) {
<span style=«white-space: pre;«> </span>$refer_string = parse_url($refer, PHP_URL_QUERY);
<span style=«white-space: pre;«> </span>parse_str($refer_string, $vars);
<span style=«white-space: pre;«> </span>$search_terms = $vars[‘q’];
<span style=«white-space: pre;«> </span>echo ‘Welcome Google visitor! You searched for the following terms to get here: ‘;
<span style=«white-space: pre;«> </span>echo $search_terms;
};
?>
Source: WP Snippets
Advertising
90. Show Google Advert after first post
If you want to insert an advert after the first post you can use this snippet in index.php:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $loopcounter++; ?>
// the loop stuffs
<?php if ($loopcounter <= 1) { include (TEMPLATEPATH . ‘/ad.php’); } ?>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
Source: Web Designer Wall
91. Show adverts after first paragraph of post
This can be quite handy for ensuring that your advertising is up to date site wide. Open your single.php file and find this:
<?php the_content(); ?>
Replace that code with this:
<?php
$paragraphAfter= 1; //display after the first paragraph
$content = apply_filters(‘the_content’, get_the_content());
$content = explode(«</p>«, $content);
for ($i = 0; $i <count($content); $i ) {
if ($i == $paragraphAfter) { ?>
<div>Your Text / Ads Go Here</div>
<?php }
echo $content[$i] . «</p>«;
} ?>
You can change the paragraph after to whichever paragraph you want.
Source: WP Beginner
92. Show Adverts Only to Google Visitors
There are claims that visitors from search engines are more likely to click on your targeted advertisements. This snippet will let you show your adverts to visitors from Google only. Paste this into your functions file:
$ref = $_SERVER[‘HTTP_REFERER’];
$SE = array(‘/search?‘, ‘images.google.’, ‘web.info.com’, ‘search.‘, ‘del.icio.us/search’, ‘soso.com’, ‘/search/’, ‘.yahoo.’);
foreach ($SE as $source) {
if (strpos($ref,$source)!==false) {
setcookie(«sevisitor», 1, time()+3600, «/», «.wpbeginner.com»);
$sevisitor=true;
}
}
function wpbeginner_from_searchengine(){
global $sevisitor;
if ($sevisitor==true || $_COOKIE[«sevisitor»]==1) {
return >true;
}
return >false;
}
Make sure you change .wpbeginner.com to your own domain.
Place this wherever you want your ad to appear:
<?php if (function_exists(‘wpbeginner_from_searchengine’)) {
if (wpbeginner_from_searchengine()) { ?>
INSERT YOUR CODE HERE
<?php } } ?>
Source: WP Beginner
Multisite
93. Enable Multisite
No doubt all of our WPMU.org readers know this one already but to enable Mutlisite include this in your wp-config.php
.
define(‘WP_ALLOW_MULTISITE’, true);
Source: WP Theming
94. Show List of Recently Created Blogs
Show off all of your latest blogs. Insert into your functions:
<?php
/*Fetch an array of $number_blogs most recently created blogs
**@number_blogs :The number of most recently created blogs you want to show.
*/
function get_recent_blogs($number_blogs=5)
{
global $wpdb;
$blog_table=$wpdb—>blogs;
/*fetch blog_id,domain,path from wp_blogs table ,where the blog is not spam,deleted or archived order by the date and time of registration */
$query=«select blog_id,domain,path from $blog_table where public=‘1‘ and archived=‘0‘ and spam=‘0‘ and deleted=‘0‘ order by registered desc limit 0,$number_blogs»;
$recent_blogs=$wpdb—>get_results($wpdb—>prepare($query));
return $recent_blogs;
}
?>
Use the following to get its output:
<ul class=«recent-blogs»>
<?php $recent_blogs=get_recent_blogs(5);
<span style=«white-space: pre;«> </span>foreach($recent_blogs as $recent_blog):
<span style=«white-space: pre;«> </span>$blog_url=«»;
<span style=«white-space: pre;«> </span>if( defined( «VHOST» ) && constant( «VHOST» ) == ‘yes’ )
<span style=«white-space: pre;«> </span>$blog_url=«http://».$recent_blog->domain.$recent_blog—>path;
<span style=«white-space: pre;«> </span>else
<span style=«white-space: pre;«> </span>$blog_url=«http://».$recent_blog->domain.$recent_blog—>path;
<span style=«white-space: pre;«> </span>$blog_name=get_blog_option($recent_blog—>blog_id,«blogname»);
<span style=«white-space: pre;«> </span>?>
<li>
<h3><a href=«<?php echo $blog_url;?>«> </a></h3>
<span><?php echo $blog_name?></span>
</li>
<?php endforeach;?>
</ul>
Source: WPMU DEV
Gravatars
95. Gravatar for Comments
Easily include your gravatar in your comments
<?
$email = $comment->comment_author_email;
$default = «http://DOMAIN.COM/gravatar.jpg»; // enter a link to your default avatar
$size = 80; // size in px, this covers width and height
$grav_url = «http://www.gravatar.com/avatar.php?gravatar_id=» . md5($email) . «&default=» . urlencode($default) . «&size=» . $size;
?>
<img src=»<?=$grav_url ?>» height=«<?=$size ?>« width=«<?=$size ?>« alt=«gravatar» class=«gravatar» title=«<?php comment_author();?>«/>
Source: Codesnipp.it
96. Change Default Gravatar
The grey mystery man is pretty boring. And those monsters aren’t much better. You can use this to change the default gravatar.
add_filter( ‘avatar_defaults’, ‘newgravatar’ );
function newgravatar ($avatar_defaults) {
$myavatar = get_bloginfo(‘template_directory’) . ‘/images/gravatar.gif’;
$avatar_defaults[$myavatar] = «WPBeginner»;
return $avatar_defaults;
}
Source: WP Beginner
97. Use Gravatar Hovercards
Shiny shiny super shiny. Everyone likes Gravatar Hovercards
function gravatar_hovercards() {
<span style=«white-space: pre;«> </span>wp_enqueue_script( ‘gprofiles’, ‘http://s.gravatar.com/js/gprofiles.js’, array( ‘jquery’ ), ‘e’, true );
}
add_action(‘wp_enqueue_scripts’,‘gravatar_hovercards’);
Source: Otto
Misc
98. Show Tag Cloud
Does what it says – show your tag cloud.
<?php wp_tag_cloud(array(
‘smallest’ => 10, // size of least used tag
‘largest’ => 18, // size of most used tag
‘unit’ => ‘px’, // unit for sizing
‘orderby’ => ‘name’, // alphabetical
‘order’ => ‘ASC’, // starting at A
‘exclude’ => 6 // ID of tag to exclude from list
)); ?>
Source: Lava 360
99. Paypal Donate Button
Essential for non-profits and charities.
<?php
function donate_shortcode( $atts, $content = null) {
global $post;extract(shortcode_atts(array(
‘account’ => ‘your-paypal-email-address’,
‘for’ => $post—>post_title,
‘onHover’ => »,
), $atts));</p>
<p>if(empty($content)) $content=‘Make A Donation’;
return ‘<a href=«https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&amp;amp;amp;amp;amp;amp;amp;amp;amp;<span id=«IL_AD3» class=»IL_AD«>business</span>=‘.$account.‘&amp;amp;amp;amp;amp;amp;amp;amp;amp;item_name=Donation for ‘.$for.‘» title=»‘.$onHover.‘»>‘.$content.‘</a>‘;
}
add_shortcode(‘donate’, ‘donate_shortcode’);
?>
Source: Lava 360
100. Tiny URL
Everyone likes tiny, little URLS. Use this snippet to get them:
function get_tiny_url( $url )
{
$tiny_url = file_get_contents( «http://tinyurl.com/api-create.php?url=».$url );
return $tiny_url;
}
Source: Flowdrops
Well, there you go. 100 snippets. Seemed like a good idea when I started out but now I think my eyes might fall out of my head……