Top 10 WordPress hacks from June ’09

by Jean. 56 Comments -

Every month, lots of WordPress users are posting new hacks and tips about their favorite blogging platform on their own blog. Here is our personnal selection of the 10 most useful and ashtonishing WordPress hacks from June 2009.

Make your WordPress theme translatable

Using the power of .po files and this short code snippets, you can make your WordPress theme available in a wide variety of languages. This code have to be pasted in your functions.php file. The .po files should be located under your wp-content/themes/your-theme-name/languages directory.

If you’re interested in that topic, you should definitely subscribe to our RSS feed as we’re going to publish a full “Translatable WordPress themes” tutorial in a few days.

// Make theme available for translation
// Translations can be filed in the /languages/ directory
load_theme_textdomain( 'your-theme', TEMPLATEPATH . '/languages' );

$locale = get_locale();
$locale_file = TEMPLATEPATH . "/languages/$locale.php";
if ( is_readable($locale_file) )
	require_once($locale_file);

Sources : http://themeshaper.com/wordpress-theme-header-template-tutorial/

List all hooked WordPress functions

WordPress hooks are very useful because they allow you to “surcharge” an existing WP function with your own code. When something goes wrong, it should be useful to list all hooked functions for debugging purposes.
This code, which have to be pasted in your functions.php file, will display a list of all hooked WordPress functions.

function list_hooked_functions($tag=false){
 global $wp_filter;
 if ($tag) {
  $hook[$tag]=$wp_filter[$tag];
  if (!is_array($hook[$tag])) {
  trigger_error("Nothing found for '$tag' hook", E_USER_WARNING);
  return;
  }
 }
 else {
  $hook=$wp_filter;
  ksort($hook);
 }
 echo '<pre>';
 foreach($hook as $tag => $priority){
  echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>$tag</strong><br />";
  ksort($priority);
  foreach($priority as $priority => $function){
  echo $priority;
  foreach($function as $name => $properties) echo "\t$name<br />";
  }
 }
 echo '</pre>';
 return;
}

Once you pasted the code, simply use the following to display the functions:

list_hooked_functions()

Source : Rarst on http://www.wprecipes.com/list-all-hooked-wordpress-functions

Disable WordPress automatic formatting on posts using a shortcode

If like me, you often display code snippets on your WordPress blog, you know how bad WordPress automatic formatting can be. Happilly, with the help from a very cool shortcode you can be able to disable it on a certain portion of text.

function my_formatter($content) {
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);

	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}

	return $new_content;
}

remove_filter('the_content', 'wpautop');
remove_filter('the_content', 'wptexturize');

add_filter('the_content', 'my_formatter', 99);

Once done, you can use the [raw] shortcode in your posts:

[raw]Unformatted code[/raw]

Source : http://wordpress.org/support/topic/280732

How to detect the visitor browser within WordPress

You know it, cross browser compatibility is a problem to many websites. But what you probably don’t know is that WordPress have a built-in tool which can be used to retrieve the visitor’s browser.
The only thing you have to do is to paste this code in your functions.php file.

<?php
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;
}
?>

Once done, your body tag will look like this, according to the current visitor browser:

<body class="home blog logged-in safari">

And you guessed it, you just have to style it your way using the style.css file.
Source : http://www.nathanrice.net/blog/browser-detection-and-the-body_class-function/

Creating user-defined RSS feeds in WordPress

If you need a custom RSS feed, like for example, a feed indexing only somes categories + tags, or if you redirected all WordPress RSS feeds to Feedburner but still want to be able to get a category feed, the solution is to use a page template.

Simply paste the following code in a new file, save it under the name custom-feed.php and upload it on your theme directory.
Once done, simply write a new page in WordPress Dashboard (Don’t type any text it in), and select custom-feed.php as a page template. If you don’t know anything about WordPress page templates, then you should start by checking out this article.

<?php
/*
Template Name: Custom Feed
*/

$numposts = 5;

function yoast_rss_date( $timestamp = null ) {
  $timestamp = ($timestamp==null) ? time() : $timestamp;
  echo date(DATE_RSS, $timestamp);
}

function yoast_rss_text_limit($string, $length, $replacer = '...') {
  $string = strip_tags($string);
  if(strlen($string) > $length)
    return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
  return $string;
}

$posts = query_posts('showposts='.$numposts);

$lastpost = $numposts - 1;

header("Content-Type: application/rss+xml; charset=UTF-8");
echo '<?xml version="1.0"?>';
?><rss version="2.0">

<channel>
  <title>Yoast E-mail Update</title>
  <link>http://yoast.com/</link>
  <description>The latest blog posts from Yoast.com.</description>

  <language>en-us</language>
  <pubDate><?php yoast_rss_date( strtotime($ps[$lastpost]->post_date_gmt) ); ?></pubDate>
  <lastBuildDate><?php yoast_rss_date( strtotime($ps[$lastpost]->post_date_gmt) ); ?></lastBuildDate>

  <managingEditor>joost@yoast.com</managingEditor>
<?php foreach ($posts as $post) { ?>
  <item>
    <title><?php echo get_the_title($post->ID); ?></title>
    <link><?php echo get_permalink($post->ID); ?></link>

    <description><?php echo '<![CDATA['.yoast_rss_text_limit($post->post_content, 500).'<br/><br/>Keep on reading: <a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>'.']]>';  ?></description>

    <pubDate><?php yoast_rss_date( strtotime($post->post_date_gmt) ); ?></pubDate>
    <guid><?php echo get_permalink($post->ID); ?></guid>
  </item>
<?php } ?>

</channel>
</rss>

Source : Yoast on http://www.wprecipes.com/creating-user-defined-rss-feeds-in-wordpress

Display your tags in a dropdown menu

In my opinion, tag clouds are not easily readables. A better way to display your tags is to use a dropdown menu. The code below consists of a function which have to be pasted in your functions.php file. Once you have the function, you’ll have to call it to create the dropdown menu, as shown in the second code example.

<?php
function dropdown_tag_cloud( $args = '' ) {
	$defaults = array(
		'smallest' => 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(' ', '&nbsp;', wp_specialchars( $tag ));
		$a[] = "\t<option value='$tag_link'>$tag ($count)</option>";
	}

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

Once you’ve pasted the function on your functions.php file, you can use it to get your dropdown menu of tags.
Just open the file where you want the list to be displayed (Most of the time it is sidebar.php) and paste the following code:

<select name="tag-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
	<option value="#">Liste d'auteurs</option>
	<?php dropdown_tag_cloud('number=0&order=asc'); ?>
</select>

Source : http://www.wprecipes.com/wordpress-hack-display-your-tags-in-a-dropdown-menu

Retrieving custom fields outside the loop

Custom fields are one of the most usefull WordPress function for customizing themes, because they allow you to add any kind of information you need to your posts.
The only problem is to be able to retrieve custom fields outside the WordPress loop. Happilly, this code can do that.

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'customField', true);
?>

Source : http://www.wprecipes.com/wordpress-how-to-get-custom-fields-outside-the-loop

Create custom “Read more” links on your WordPress blog

To achieve this hack, the first step is to edit your posts and create custom fields.
Give them custom_more as a key, and the text to display as a value.
Once done, edit your index.php file (As well as category.php, search.php, etc) and find a line similar to this:

the_content("Read more");

Simply replace it with this code:

<?php $custommore = get_post_meta($post->ID, 'custom_more', true); ?>
<?php if (!$custommore) { $custommore = 'Read More &raquo;'; } ?>
<?php the_content($custommore); ?>

Allright, you’re done.
Now, if you create a custom field named custom_more, its value will be displayed instead of the classic “Read more” link.
Source : http://www.cagintranet.com/archive/wordpress-tip-3-awesome-custom-field-tricks/

Get tags specific to a particular category on your WordPress blog

As I said before, tag clouds are quite unreadable. Another clever way to display them is to use only the tags related to a specific category.

This code will output all tags related to a category. Don’t forget to change the category name on line 2.

<?php
	query_posts('category_name=work&showposts=-1');
	if (have_posts()) : while (have_posts()) : the_post();
        $posttags = get_the_tags();
		if ($posttags) {
			foreach($posttags as $tag) {
				$all_tags_arr[] = $tag -> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
			}
		}
	endwhile; endif; 

	$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
	//echo '<pre>'.print_r($tags_arr, true).'</pre>';
       
       foreach ($tags_arr as $tag) {
           echo '<li><a href="http://yourblog.com/tag/'.$tag.'">'.$tag.'</a></li>';
       }

?>

Source : http://www.wprecipes.com/get-tags-specific-to-a-particular-category-on-your-wordpress-blog

Get rid of auto media enclosures on your WordPress blog

When you’re adding a multimedia file as such as a mp3 or flv file, WordPress automatically create a custom field named enclosure and add the media url to your rss feed. While this is great for podcasters, it is unusefull for most bloggers.

The code below will disable automatic media enclosures. Just paste it on your functions.php file, save the file, and you’ll be done!

function delete_enclosure(){
    return '';
}
add_filter( 'get_enclosed', 'delete_enclosure' );
add_filter( 'rss_enclosure', 'delete_enclosure' );
add_filter( 'atom_enclosure', 'delete_enclosure' );

Source : http://www.webinventif.fr/empecher-enclosure-automatique-wordpress/

Want more WordPress hacks and tips?

If your answer to the above question was a definitive “YES!”, I urge you to visit my other blog, WpRecipes, which provide daily WordPress hacks to do everything with your WP blog.