19 Useful WordPress Snippets & Tutorials


1. Use your blog gravatar as favicon

[php]

<?php
function GravatarAsFavicon() {
//We need to establish the hashed value of your email address
$GetTheHash = md5(strtolower(trim(‘[email protected]’)));
echo ‘http://www.gravatar.com/avatar/’ . $GetTheHash . ‘?s=16′;
}

?>[/php]

Then add the following code in your header.php file

[php]

<link rel="shortcut icon" href="<?php GravatarAsFavicon(); ?>" />

[/php]

source : http://wp-snippets.com/gravatar-as-favicon

2. Change the default from addresses when WordPress sends out its emails

Add this to functions.php to change the default from addresses when WordPress sends out its emails

[php]

<?php
add_filter(‘wp_mail_from’, ‘new_mail_from’);
add_filter(‘wp_mail_from_name’, ‘new_mail_from_name’);

function new_mail_from($old) {
return ‘[email protected]';
}

function new_mail_from_name($old) {
return ‘Dave Thomas';
}
?>

[/php]

3. How to change WordPress editor font

If you want t chanege the WordPress visual Editor font then simply add the following code in yoyr function.php file.You can modify the code with your favorite font.

[php]

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 }

[/php]

source : http://www.wprecipes.com/how-to-change-wordpress-editor-font-2

4. Set the content type email from text/plain to text/html

Add the below code in your functions.php file

[php]

function wps_set_content_type(){
return "text/html";
}
add_filter( ‘wp_mail_content_type’,’wps_set_content_type’ );
[/php]

source : http://wpsnipp.com/index.php/functions-php/set-the-content-type-email-from-textplain-to-texthtml

5. Use Shortcodes in Widgets

Paste the following code to your functions.php file

[php]

// shortcode in widgets

if ( !is_admin() ){

add_filter(‘widget_text’, ‘do_shortcode’, 11);

}

[/php]

source :http://wpshout.com/wordpress-functions-php

6. Display attachment thumbnail with image metadata

Adding this snippet within the loop of your index.php template file will display a list of all post attachments with the following metadata (Credit, Camera, Focal Length, Aperture, ISO, Shutter Speed, Time Stamp, Copyright).

[php]

<?php
if($images =& get_children( ‘post_type=attachment’ )){
foreach($images as $id => $attachment ){
echo ”;
echo wp_get_attachment_image( $id, ‘thumb’ )."<br />";
$meta = wp_get_attachment_metadata($id);
echo "Credit: ".$meta[image_meta][credit]."<br /> ";
echo "Camera: ".$meta[image_meta][camera]."<br />";
echo "Focal length: ".$meta[image_meta][focal_length]."<br />";
echo "Aperture: ".$meta[image_meta][aperture]."<br />";
echo "ISO: ".$meta[image_meta][iso]."<br />";
echo "Shutter speed: ".$meta[image_meta][shutter_speed]."<br />";
echo "Time Stamp: ".$meta[image_meta][created_timestamp]."<br />";
echo "Copyright: ".$meta[image_meta][copyright];
echo ”;
}
}
?>

[/php]

source : http://wpsnipp.com/index.php/loop/display-attachment-thumbnail-with-image-metadata

7. Check if user is using StumbleUpon

Display a special message to only your stumbleupon visitors.This conditional tag checks if the user comes from StumbleUpon.Add the below snippet in your header.php file
Note: this doesn’t work if the user are using a browser toolbar, since it checks the URL for stumbleupon.com.

[php]

<?php if( strpos($_SERVER[HTTP_REFERER], "stumbleupon.com" ) == true ): ?>
<div class="welcome-stumbleupon">
<p>Hello StumbleUpon user!</p>

<?php endif; ?>
[/php]

source : http://wp-snippets.com/check-if-user-is-using-stumbleupon

8. Display the comment count using a shortcode

Adding this snippet to the functions.php of your wordpress theme will let you display the comment count for any post by simply using this shortcode [comments id="23" ]

[php]

function comments_shortcode($atts) {
extract( shortcode_atts( array(
‘id’ => ”
), $atts ) );
$num = 0;
$post_id = $id;
$queried_post = get_post($post_id);
$cc = $queried_post->comment_count;
if( $cc == $num || $cc > 1 ) : $cc = $cc.’ Comments';
else : $cc = $cc.’ Comment';
endif;
$permalink = get_permalink($post_id);
return ‘<a href="’. $permalink . ‘">’ . $cc . ‘</a>';
}
add_shortcode(‘comments’, ‘comments_shortcode’);
[/php]

source : http://wpsnipp.com/index.php/comment/display-the-comment-count-using-a-shortcode

9. Show WordPress Child Pages Alongside Parent Page

This goes in your page template or sidebar template where you want your submenu to appear. It is outside the loop.

[php]

post_parent);
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");

if ($children && is_page()) { ?>
<div class="subnav">
<ul>
<li><a href="<?php echo get_permalink($post->post_parent) ?>"></a></li>
</ul>

[/php]

source : http://vonlind.com/2011/04/show-wordpress-child-pages-alongside-parent-page

10. How To Automatically Add FTP Detail on WordPress

Open your wp-config.php and add this code

[php]

define(‘FTP_HOST’, ‘Your_FTP_Hosting’);
define(‘FTP_USER’, ‘Your_FTP_Username’);
define(‘FTP_PASS’, ‘Your_FTP_Password);
//If you use SSL connection, set this to true
define(‘FTP_SSL’, false);

[/php]

source : http://wptricks.net/how-to-automatically-added-ftp-detail-on-wordpress

11. How to Remove the “read more” Jump

Paste the below code in your functions.php file

[php]

function wdc_no_more_jumping($post) {
return ‘<a href="’.get_permalink($post->ID).’">’.’Continue Reading’.'</a>';
}
add_filter(‘excerpt_more’, ‘wdc_no_more_jumping’);

[/php]

source : http://www.wprecipes.com/how-to-remove-the-read-more-jump

12. How to Disable Self Trackbacks

Paste the following code to your functions.php file

[php]

function disable_self_ping( &$links ) {
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, get_option( ‘home’ ) ) )
unset($links[$l]);
}
add_action( ‘pre_ping’, ‘disable_self_ping’ );

[/php]

13. How to Display Most Commented Posts of Specific Year Without Plugin

Paste the following code in the sidebar.php or where ever you want.

[php]

<ul>
get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN ‘YEAR-MM-DD (start)’ AND ‘YEAR-MM-DD (end)’ ORDER BY comment_count DESC LIMIT 0 , 10");

foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ($commentcount != 0) {
?>

</ul>

[/php]

14. How to Display Tags as Dropdown

Add the below code to your function.php you will turn your standard tag cloud as a cool dropdown menu.

[php]

8, ‘largest’ => 22, ‘unit’ => ‘pt’, ‘number’ => 45,
‘format’ => ‘flat’, ‘orderby’ => ‘name’, ‘order’ => ‘ASC’,
‘exclude’ => ”, ‘include’ => ”
);
$args = wp_parse_args( $args, $defaults );

$tags = get_tags( array_merge($args, array(‘orderby’ => ‘count’, ‘order’ => ‘DESC’)) ); // Always query top tags

if ( empty($tags) )
return;

$return = dropdown_generate_tag_cloud( $tags, $args ); // Here’s where those top tags get sorted according to $args
if ( is_wp_error( $return ) )
return false;
else
echo apply_filters( ‘dropdown_tag_cloud’, $return, $args );
}

function dropdown_generate_tag_cloud( $tags, $args = ” ) {
global $wp_rewrite;
$defaults = array(
‘smallest’ => 8, ‘largest’ => 22, ‘unit’ => ‘pt’, ‘number’ => 45,
‘format’ => ‘flat’, ‘orderby’ => ‘name’, ‘order’ => ‘ASC’
);
$args = wp_parse_args( $args, $defaults );
extract($args);

if ( !$tags )
return;
$counts = $tag_links = array();
foreach ( (array) $tags as $tag ) {
$counts[$tag->name] = $tag->count;
$tag_links[$tag->name] = get_tag_link( $tag->term_id );
if ( is_wp_error( $tag_links[$tag->name] ) )
return $tag_links[$tag->name];
$tag_ids[$tag->name] = $tag->term_id;
}

$min_count = min($counts);
$spread = max($counts) – $min_count;
if ( $spread <= 0 )
$spread = 1;
$font_spread = $largest – $smallest;
if ( $font_spread <= 0 ) $font_spread = 1; $font_step = $font_spread / $spread; // SQL cannot save you; this is a second (potentially different) sort on a subset of data. if ( ‘name’ == $orderby ) uksort($counts, ‘strnatcasecmp’); else asort($counts); if ( ‘DESC’ == $order ) $counts = array_reverse( $counts, true ); $a = array(); $rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ‘ rel="tag"’ : ”;

foreach ( $counts as $tag => $count ) {
$tag_id = $tag_ids[$tag];
$tag_link = clean_url($tag_links[$tag]);
$tag = str_replace(‘ ‘, ‘ ‘, wp_specialchars( $tag ));
$a[] = "\t$tag ($count)";
}

switch ( $format ) :
case ‘array’ :
$return =& $a;
break;
case ‘list’ :
$return = "
<ul class="wp-tag-cloud">\n\t
<li>";
$return .= join("</li>
\n\t
<li>", $a);
$return .= "</li>
\n</ul>
\n";
break;
default :
$return = join("\n", $a);
break;
endswitch;

return apply_filters( ‘dropdown_generate_tag_cloud’, $return, $tags, $args );
}
?>
[/php]

source : http://www.wpcode.net/tag-cloud-dropdown.html

14. How To Add More Button on Visual Mode WordPress Editor

Open functions.php on your current theme using your favorite editor and add this code.

[php]

function add_more_buttons($buttons) {
$buttons[] = ‘hr';
$buttons[] = ‘del';
$buttons[] = ‘sub';
$buttons[] = ‘sup';
$buttons[] = ‘fontselect';
$buttons[] = ‘fontsizeselect';
$buttons[] = ‘cleanup';
$buttons[] = ‘styleselect';
return $buttons;
}
add_filter("mce_buttons_3", "add_more_buttons");

[/php]

15. How To Move the Admin Bar to the Bottom

Copy and paste this code and place it on your functions.php

[php]

// move admin bar to bottom
function fb_move_admin_bar() { ?>
<!–
body {
margin-top: -28px;
padding-bottom: 28px;
}
body.admin-bar <a href="http://search.twitter.com/search?q=%23wphead" class="tweet-hashtag">#wphead</a> {
padding-top: 0;
}
body.admin-bar <a href="http://search.twitter.com/search?q=%23footer" class="tweet-hashtag">#footer</a> {
padding-bottom: 28px;
}
<a href="http://search.twitter.com/search?q=%23wpadminbar" class="tweet-hashtag">#wpadminbar</a> {
top: auto !important;
bottom: 0;
}
<a href="http://search.twitter.com/search?q=%23wpadminbar" class="tweet-hashtag">#wpadminbar</a> .quicklinks .menupop ul {
bottom: 28px;
}

–>
// on backend area
add_action( ‘admin_head’, ‘fb_move_admin_bar’ );
// on frontend area
add_action( ‘wp_head’, ‘fb_move_admin_bar’ );

[/php]

source : http://wptricks.net/how-to-move-move-the-admin-bar-to-the-bottom

17. Add Google+ button to your posts automatically

Google+ is a new “social” service offered by Internet giant Google. If you want to let your visitor “plus” your post, why not adding a Google+ button to all of your entries automatically?

Simply paste the code below into your functions.php file. Once you saved the file, the Google+ button will be automatically displayed near your posts.

[php]

add_filter(‘the_content’, ‘wpr_google_plusone’);
function wpr_google_plusone($content) {
$content = $content.'<g:plusone size="tall" href="’.get_permalink().’"></g:plusone>';
return $content;
}
add_action (‘wp_enqueue_scripts’,’wpr_google_plusone_script’);
function wpr_google_plusone_script() {
wp_enqueue_script(‘google-plusone’, ‘https://apis.google.com/js/plusone.js’, array(), null);
}
[/php]

Source: http://www.wprecipes.com/wordpress-hook-automatically-add-a-google-button-to-your-posts

18. Redirect RSS feeds to Feedburner

Feedburner is a well known service that let you know how many people have subscribed to your RSS feeds. Instead of tweaking your theme to replace links to WordPress built-in feed, you should definitely use this hook which automatically redirect all WordPress feeds to your Feedburner feeds.

Edit line 4 and replace my feed url by yours. Once done, paste the code in your functions.php file. Save the file, and you’re done!

[php]

add_action(‘template_redirect’, ‘cwc_rss_redirect’);
function cwc_rss_redirect() {
if ( is_feed() && !preg_match(‘/feedburner|feedvalidator/i’, $_SERVER['HTTP_USER_AGENT'])){
header(‘Location: http://feeds.feedburner.com/catswhocode’);
header(‘HTTP/1.1 302 Temporary Redirect’);
}
}
[/php]

Source: http://wp.smashingmagazine.com/2011/12/07/10-tips-optimize-wordpress-theme/

19. Track post views without using a plugin

Are you curious about how many people are reading your posts? A few “view counts” plugins exists, but here’s a simple way to do this yourself. The first thing to do is to create the functions. Paste the code below into your functions.php file.

[php]

function getPostViews($postID){
$count_key = ‘post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==”){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0’);
return "0 View";
}
return $count.’ Views';
}
function setPostViews($postID) {
$count_key = ‘post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==”){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, ‘0’);
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
<p style="text-align: justify;">[/php]

Then, paste the code below within the single.php within the loop:

[php]</p>

<?php setPostViews(get_the_ID()); ?>
<p style="text-align: justify;">[/php]

Finally, paste the snippet below anywhere within the template where you would like to display the number of views:

[php]</p>

<?php echo getPostViews(get_the_ID()); ?>
<p style="text-align: justify;">[/php]

source : http://wpsnipp.com/index.php/functions-php/track-post-views-without-a-plugin-using-post-meta