65
Closing Comment after 30 days To enable auto comment closing, simply paste the following function on the functions.php file from your theme. If that file doesn't exists, create it. <?php function close_comments( $posts ) { if ( !is_single() ) { return $posts; } if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) { $posts[0]->comment_status = 'closed'; $posts[0]->ping_status = 'closed'; } return $posts; } add_filter( 'the_posts', 'close_comments' ); ?> You can easily change the number of days after posts can't be commented by changing 30 to X on line 3 of the close_comments() function. Disable all plugins UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins'; Display only the Latest Sticky Post Open your index.php file, and replace your current loop by this one (replacing the stickies category name by the category of your choice) by : <?php if (have_posts()) : $my_query = new WP_Query('category_name=stickies&showposts=1'); while ($my_query->have_posts()) : $my_query->the_post(); ?>

Wordpress Cheats

Embed Size (px)

Citation preview

Page 1: Wordpress Cheats

Closing Comment after 30 days

To enable auto comment closing, simply paste the following function on the functions.php file from your theme. If that file doesn't exists, create it.

<?phpfunction close_comments( $posts ) {

if ( !is_single() ) { return $posts; }if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24

* 60 * 60 ) ) {$posts[0]->comment_status = 'closed';$posts[0]->ping_status = 'closed';

}return $posts;

}add_filter( 'the_posts', 'close_comments' );?>

You can easily change the number of days after posts can't be commented by changing 30 to X on line 3 of the close_comments() function.

Disable all plugins

UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins';

Display only the Latest Sticky Post

Open your index.php file, and replace your current loop by this one (replacing the stickies category name by the category of your choice) by :

<?php if (have_posts()) :$my_query = new WP_Query('category_name=stickies&showposts=1');while ($my_query->have_posts()) : $my_query->the_post(); ?>

That's all! Only the latest post is displayed on your homepage.

Hide Wordpress Version

This hack isn’t hard to do at all. Just open the functions.php file from your theme and add the following line of code:

remove_action('wp_head', 'wp_generator');

Page 2: Wordpress Cheats

On the above code, I just used the remove_action to remove the wp_generator() function, which prints out WP version. As that function will now not be executed, the WordPress version will not be visible from your source code, and potential hackers will never know which version you are using.

Create a Save to Delicious button

This recipe is very easy to achieve: Paste the following code within the loop, on your single.php file.

<a href="http://del.icio.us/post?url=<?php the_permalink();?>">Save this link to Delicious</a>

Number of times a articles is saved to Delicious

To get your Delicious save count in plain text, simply open the single.php file from your theme and paste the following code where you'd like the count to be displayed.

Delicous.com saves: <span id='del'>0</span>

<script type='text/javascript'>function displayURL(data) { var urlinfo = data[0]; if (!urlinfo.total_posts) return; document.getElementById("del").innerHTML = urlinfo.total_posts;}</script>

<script src='http://badges.del.icio.us/feeds/json/url/data?url=<?php the_permalink() ?>&callback=displayURL'></script>

Meta Description Function

Open your header.php file. Paste the following code anywhere within the <head> and </head> tags:

<meta name="description" content="<?php if ( (is_home()) || (is_front_page()) ) { echo ('Your main description goes here');} elseif(is_category()) { echo category_description();} elseif(is_tag()) { echo '-tag archive page for this blog' . single_tag_title();} elseif(is_month()) { echo 'archive page for this blog' . the_time('F, Y');} else { echo get_post_meta($post->ID, "Metadescription", true);}?>">

Page 3: Wordpress Cheats

To Check if the Post has excerpt

To check out if a post has an excerpt, simply paste the following code within the loop:

<?php if(!empty($post->post_excerpt)) { //This post have an excerpt, let's display it the_excerpt(); } else { // This post have no excerpt } ?>

Making New Posts Stand Out

To achieve this recipe, edit your index.php file and look for the loop. Replace it with that one:

<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); $currentdate = date('Y-m-d',mktime(0,0,0,date('m'),date('d'),date('Y'))); $postdate = get_the_time('Y-m-d'); if ($postdate==$currentdate) { echo '<div class="post new">'; } else { echo '<div class="post">'; } ?> <a href="<?php the_permalink() ?>" rel="bookmark"> <?php the_title(); ?></a> <?php the_time('j F Y'); ?> </div> <?php endwhile; ?><?php endif; ?>

The above code will add the css class new if the post was published less than 24 hours ago. Then, you just have to modify your stylesheet a bit:

.post{ /* CSS style for "normal" posts */}

.post.new { /* CSS style for newer posts */}

Page 4: Wordpress Cheats

Integrate Files in the Blog Header

The principe is simple: You first got top create a function that will simply print the required files. Then, you got to hook it to the wp_head() WordPress function, by using the add_action() function.

function GetLastPostName_head(){ echo '<script type="text/javascript" src="'.get_settings('siteurl').'/wp-content/plugins/slidelastposttitle/mootools.js"></script>'; echo '<script type="text/javascript" src="'.get_settings('siteurl').'/wp-content/plugins/slidelastposttitle/blackbox.js"></script>';}add_action('wp_head', 'GetLastPostName_head');

Access data outside Loop

To achieve this recipe, paste the following function on the functions.php file from your theme.This function takes a singles argument, which is the ID of the post you'd like to access data. It will return an array, containing post title, date, content, author id, post id, etc.

function get_post_data($postId) { global $wpdb; return $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID=$postId");}

To use the function, use the following anywhere on your theme files:

<?php$data = get_post_data(10);echo $data[0]->post_title; //Print post titleecho $data[0]->post_date; //Print post dateecho $data[0]->comment_count; //Print number of commentsecho $data[0]->post_content; /Print post content?>

Use HTML in Author Profiles

To be able to use html in user profiles, simply append the following line of code to the functions.php file from your theme. (Create that file if it doesn't exists)

remove_filter('pre_user_description', 'wp_filter_kses');

Page 5: Wordpress Cheats

That's all, authors are now allowed to use html in their profiles!

Get the value of Custom Field

Here's the function. You have to paste it on your theme functions.php file. If your theme doesn't have a file named functions.php, create one.

function get_custom_field_value($szKey, $bPrint = false) {global $post;$szValue = get_post_meta($post->ID, $szKey, true);if ( $bPrint == false ) return $szValue; else echo $szValue;

}

Now, to call the function and get your custom field value, use the following code:

<?php if ( function_exists('get_custom_field_value') ){ get_custom_field_value('featured_image', true);} ?>

First, we use the php function_exists() function to make sure the get_custom_field_value function is defined on our theme. If it is, we use it. The first argument is the custom field name (here, featured_image) and the second let you echo the value (true) or get it for further use in php (false).

Stop Spam in Comments by checking Referrer

To achieve this recipe, simple paste the following code on your .htaccess file, located at the root of your WordPress install. Don't forget to specify your blog url on line 4.Remember to ALWAYS create a backup when editing the .htaccess file.

RewriteEngine OnRewriteCond %{REQUEST_METHOD} POSTRewriteCond %{REQUEST_URI} .wp-comments-post\.php*RewriteCond %{HTTP_REFERER} !.*yourblog.com.* [OR]RewriteCond %{HTTP_USER_AGENT} ^$RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

The above code looks for the referer (The url from where the page has been called) when the wp-comments-post.php file is accessed. If a referer exists, and if it is your blog url, the comment is allowed. Otherwise, the sapm bot is redirected and the comment will not be posted.

Access Wordpress Options Table

Page 6: Wordpress Cheats

To easily access to the wp-options table, juste enter the following url in your browser adress bar:

http://www.yourblog.com/wp-admin/options.php

You'll see a control panel appearing. From it, you can modify almost all data recorded in the wp-options table. Of course, don't do anything unless you know what you're doing!

Redirect users to a specific URL using

To create a 301 redirection within WordPress, you just have to add the 301 argument to the function:

<?php wp_redirect('http://www.wprecipes.com', 301); ?>

The above code will redirect anyone on my blog

Automatically remove code mistakes from the Post

To achieve this recipe, you first have to creat the function which will takes your post content, clean it and print or return it.

Page 7: Wordpress Cheats

Copy the code below to the functions.php file from your theme. Create that file if it doesn't exists.

function clean_bad_content( $bPrint = false ){global $post;$szPostContent = $post->post_content;$szRemoveFilter = array( "~<p[^>]*>\s?</p>~",

"~<a[^>]*>\s?</a>~", "~<font[^>]*>~", "~<\/font>~", "~style\=\"[^\"]*\"~", "~<span[^>]*>\s?</span>~" );

$szPostContent = preg_replace( $szRemoveFilter, '' , $szPostContent);

$szPostContent = apply_filters('the_content', $szPostContent);if ( $bPrint == false ) return $szPostContent; else echo

$szPostContent;}

Proceed as the following to display your clean post content:

<?php if ( function_exists( 'clean_bad_content' ) ) clean_bad_content( true ); ?>

The clean_bad_content() only takes one argument, a boolean to specify if you'd like to print the result (true) , or get it for further use in php (false).

Display the total number of TrackBacks

To achieve this recipe, we first have to create a function. paste the following code on the functions.php file from your theme:

function tb_count() { global $wpdb;

$count = "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_type = 'pingback' OR comment_type = 'trackback'"; echo $wpdb->get_var($count);}

Once the file is saved, you can call the function anywhere you want:

<?php tb_count(); ?>

Using Wordpress ShortCodes

To create a shortcode, you first have to create a php function. Let's start with a basic one. Append it to your functions.php file.

function wprecipes() {

Page 8: Wordpress Cheats

return 'Have you checked out <a href="http://www.wprecipes.com">WpRecipes</a> today?';}

Once you created your function, you have to use the add_shortcode() function. paste this code just after your function on the functions.php file from your theme:

add_shortcode('wpr', 'wprecipes');

You're now able to use the wpr shortcode. To do so, paste the following line of code on the editor (in HTML mode) while writing a post:

[wpr]

This short code will output the "Have you checked out WpRecipes today?" message.

Getting Permalink outside Loop

To get a permalink outside of the loop, you have to use the get_permalink() function. That function takes a single argument, which is the ID of the post you'd like to get the permalink:

<a href="<?php echo get_permalink(10); ?>" >Read the article</a>

You can also use this function with the $post global variable:

<a href="<?php echo get_permalink($post->ID); ?>" >Read the article</a>

Using Wordpress Shortcode using Attribute

Adding attributes to your shortcodes isn't that hard. First, make sure that you have read and understand this recipe about creating shortcodes.

Paste the following code on the functions.php file from your theme.

function myUrl($atts, $content = null) {extract(shortcode_atts(array(

"href" => 'http://'), $atts));return '<a href="'.$href.'">'.$content.'</a>';

}add_shortcode("url", "myUrl");

As you can see on the above code, I have defined a default value for the href attribute on line 3. I'm using this value on the last line, as the value of the html href attribute.

Page 9: Wordpress Cheats

When you're writing a post/page, insert the following code in the html editor:

[url href="http://www.wprecipes.com"]WordPress recipes[/url]

It will display a link, titled WordPress recipes to http://www.wprecipes.com.

Number of Comments of Each Post

To achieve this recipe, simply open your index.php file and paste the following code within the loop:

<?php comments_number('No comments yet','1 comment','% comments')?>

Even better, this simple line of code have a link to jump directly to the comments:

<a href="<?php the_permalink() ?>#comments"><?php comments_number('No comments yet','1 comment','% comments')?></a>

If you enjoyed this article, please consider sharing i

Hack Insert Ads into RSS feeds

If you have problem while using the recipe here, try that one:Simply paste the following code on the functions.php file from your theme. Create that file if it doesn't exists by default.

function insertRss($content) { if(is_feed()){ $content = 'text before content'.$content.'<hr /><a href="http://www.wprecipes.com">Did you visited WpRecipes today?</a><hr />'; } return $content;}add_filter('the_content', 'insertRss');

Another great way to insert ads or anything in to your rss feed is the Rss Footer plugin by Joost de Valk.

Insert ads into RSS feeds

n order to achieve this recipe, paste the code below to the functions.php file from your theme. If your theme doesn't have a functions.php file, create it.

Page 10: Wordpress Cheats

<?phpfunction insertAds($content) { $content = $content.'<hr /><a href="http://www.wprecipes.com">Have you visited WpRecipes today?</a><hr />'; return $content;}add_filter('the_excerpt_rss', 'insertAds');add_filter('the_content_rss', 'insertAds');?>

Here, we first create a function called insertAds(), which concatenate a code containing our advertisment to the $content variable, which contains the content of the post.Then, we use the add_filter() function to overwrite the the_content_rss() function with our insertAds() function. We use another filter to overwrite the_excerpt_rss() function as well.That's all, your rss feeds now displays your ads!

Embeded Adsense anywhere in Post

First, you have to add the following code to your function.php file. Don't forget to change the adsense code, unless you'd like to display my ads on your own site

function showads() { return '<script type="text/javascript"><!--google_ad_client = "pub-3637220125174754";google_ad_slot = "4668915978";google_ad_width = 468;google_ad_height = 60;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>';}

add_shortcode('adsense', 'showads');

Once you saved the functions.php file, you're now able to embed your adsense code on your posts and display it exactly where you want. To do so, simply paste the following code on the editor, in html mode:

[adsense]

Page 11: Wordpress Cheats

Add shortcodes in Sidebars

To allow shortcodes in sidebar widgets, simply edit the functions.php file from your them and add the following code:

add_filter('widget_text', 'do_shortcode');

Once you saved the file, you can now add as many shortcodes as you want in sidebar widgets.

Use 2 or More loops without Duplicating Post

To avoid post duplication, I started by creating a php array, and adding the IDs of the posts I get in the first loop to that array:

<h2>Loop n°1</h2><?php$ids = array();while (have_posts()) : the_post();the_title();?><br />

<?php $ids[]= $post->ID;endwhile; ?>

Now, the second loop: I have used the php function in_array() to check out if a post ID is contained in the $ids array. If the IDs isn't contained in the array, we can display the post as it wasn't displayed on the first loop.

<h2>Loop n°2</h2><?phpquery_posts("showposts=50");while (have_posts()) : the_post();if (!in_array($post->ID, $ids)) { the_title();?> <br /><?php }endwhile; ?>

That's done: No duplicated post!Alternatively, it is possible to transform the $ids array to a comma separated string and use in along with the exclude parameter of the query_post() function.

Page 12: Wordpress Cheats

Excluding Posts/Pages from Wordpress Search

To achieve this recipe, simply paste the following code on the functions.php file from your theme. In this example, posts with IDs 8 and 15 will be excluded from your blog’s search results:

function SearchFilter($query) { if ($query->is_search) { $query->set('cat','8,15'); } return $query;}

add_filter('pre_get_posts','SearchFilter');

Get Posts having a specific Custom field

The answer to Tomas question is quite simple. What I've done is simply using a normal loop (That you can enhance with query_post() for exemple) and then, using a conditional instruction to check out if the post have the esired custom field.

<?php if (have_posts()) : while (have_posts()) : the_post(); $customField = get_post_custom_values("img"); if (isset($customField[0])) { //Custom field is set, display post info the_title(); the_excerpt(); } endwhile;endif;?>

Retrieve Image in Post Content

To achieve this recipe, simply paste the following code on one of your theme files. It will search for all images contained in the post content, and display it.

<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>

<?php$szPostContent = $post->post_content;$szSearchPattern = '~<img [^\>]*\ />~';

// Run preg_match_all to grab all the images and save the results in $aPicspreg_match_all( $szSearchPattern, $szPostContent, $aPics );

Page 13: Wordpress Cheats

// Check to see if we have at least 1 image$iNumberOfPics = count($aPics[0]);

if ( $iNumberOfPics > 0 ) { // Now here you would do whatever you need to do with the images // For this example the images are just displayed for ( $i=0; $i < $iNumberOfPics ; $i++ ) { echo $aPics[0][$i]; };};

endwhile;endif;?>

Get Post having a specific Custom Field and a Specific Value

The code is basically the same, we just have to verify if the custom field is set and if its value is the one we expect. If yes, we display the post info.

<?php if (have_posts()) : while (have_posts()) : the_post(); $customField = get_post_custom_values("img"); if ( (isset($customField[0])) && ($customField[0] == "myValue") ) { //Custom field have myValue as a value, display info the_title(); the_excerpt(); } endwhile;endif;?>

Display Message on a Specific Date

To achieve this very simple recipe, simply paste the following code anywhere on your theme. The "Merry Christmas" message will be displayed only on Christmas day.

<?phpif ((date('m') == 12) && (date('d') == 25)) { ?> <h2>Merry Christmas from WpRecipes!</h2><?php } ?>

Page 14: Wordpress Cheats

Hide Sidebar in the Blog Homepage

To hide your sidebar on your blog homepage, edit the index.php file from your theme and look the the following:

<?php get_sidebar(); ?>

Replace it by the code above:

<?php if (!is_front_page()) { get_sidebar();} ?>

Make Title Tag SEO friendly

Open your header.php file for edition. find the <title> tag, and replace it by the following code:

<title><?php if (is_home () ) { bloginfo('name');} elseif ( is_category() ) { single_cat_title(); echo ' - ' ; bloginfo('name');} elseif (is_single() ) { single_post_title();} elseif (is_page() ) { bloginfo('name'); echo ': '; single_post_title();} else { wp_title('',true);} ?></title>

This code will generate title tags according to the following model:

If the visitor is on the blog homepage: We'll display the blog name. If the visitor is on a category page: We'll display the category name and the blog

name. If the visitor is on an article page: We'll only display the article title. If the visitor is on a static page: We'll display the blog name, and the page title.

Highlight the Current Category

When you're browsing a category, WordPress automatically add a current-cat css class to the <li> element.

Page 15: Wordpress Cheats

So the only thing you have to do is to edit your style.css file and add a style for the current-cat class:

#nav .current-cat{ background:#999; color:#222; text-decoration:underline;}

Embedded CSS in Post with a Custom Field

First, open your header.php file and insert the following code between the <head> and </head> html tags:

<?php if (is_single()) { $css = get_post_meta($post->ID, 'css', true); if (!empty($css)) { ?> <style type="text/css"> <?php echo $css; ?> <style> <?php }} ?>

Once done, when you're writing a post or page which require some custom css styling, you'll just have to create a custom field named css and paste your custom css styles as a value. That's simple as that!

Control when your post are available in RSS

To achieve this recipe, simply paste the following code into your theme's function.php file. If your theme doesn't have this file, just create it.

function publish_later_on_feed($where) {global $wpdb;

if ( is_feed() ) {// timestamp in WP-format$now = gmdate('Y-m-d H:i:s');

// value for wait; + device$wait = '5'; // integer

// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff

$device = 'MINUTE'; //MINUTE, HOUR, DAY, WEEK, MONTH, YEAR

// add SQL-sytax to default $where

Page 16: Wordpress Cheats

$where.=" AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";

}return $where;

}

add_filter('posts_where', 'publish_later_on_feed');

The above code will add a 5 minutes delay between your post being published on your blog, and on your rss feed. To change the delay, change the value of the $wait variable, on line 9.

Style Author Comments

With previous WordPress versions, you had to use some hacks to be able to give a special style to author comments. But this isn't needed with the brand new WordPress 2.7: A specific CSS class is automatically added by WP to author and registered users comments.

To style author and registered users on WordPress 2.7, simply paste the following code in your style.css file, and style at your taste

li.bypostauthor { /* CSS styles for author comments */}

li.byuser { /* CSS styles for registered users comments */}

Display the most commented posts in 2008

To display a list of your 10 most commented posts from 2008, simply paste the following code on your blog sidebar, or anywhere on your theme:

<h2>Most commented posts from 2008</h2><ul><?php$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '2008-01-01' AND '2008-12-31' 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) {

Page 17: Wordpress Cheats

?> <li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li> <?php }}?></ul>

Display a random post in the Sidebar

To achieve this recipe, simply paste the following code on he sidebar.php file of your theme:

<?phpquery_posts(array('orderby' => 'rand', 'showposts' => 1));if (have_posts()) : while (have_posts()) : the_post(); the_title(); the_excerpt(); endwhile;endif; ?>

That's all. Your sidebar will display a random post on each of your blog pages.

Remove Curley Quotes from the SideBar

To achieve this recipe, simply paste the following line of code on the functions.php file from your theme.

remove_filter('comment_text', 'wptexturize');

That's easy as that! Say goodbye to broken codes!

Get a Particular Header, Footer or Sidebar

The following code will check if the reader is on the "WordPress" category. If yes, header-wordpress.php will be inclued, otherwise the default header will be used:

<?php if is_category('WordPress') { get_header('wordpress');} else { get_header();} ?>

Page 18: Wordpress Cheats

You can also use that new functionality with footers and sidebars:

<?php get_footer('myfooter'); ?>

will include footer-myfooter.php

<?php get_sidebar('mysidebar'); ?>

will include sidebar-mysidebar.php

Highlight Search text in Search Results

Open your search.php file and find the the_title() function. Replace it with the following:

echo $title;

Now, just before the modified line, add this code:

<?php$title = get_the_title();$keys= explode(" ",$s);$title = preg_replace('/('.implode('|', $keys) .')/iu',

'<strong class="search-excerpt">\0</strong>',$title);

?>

Save the search.php file and open style.css. Append the following line to it:

strong.search-excerpt { background: yellow; }

That's all. Better, isn't it?

Disable Search Engine Indexing on a Single Post

To achieve, first get the ID of the post you'd like to be not indexed by search engines. In this exemple, I assume your post id is 17.Open your header.php file and paste the following code between the <head> and </head> tags:

<?php if ($post->ID == 17) { echo '<meta name="robots" content="noindex">';}

Page 19: Wordpress Cheats

That's all. Pretty useful if you don't want some infos to be accessible from search engines!Note that it is possible to do something better by using custom fields. If you're interested about this second method, just leave a comment and I'll write a recipe!

Remove Category from Wordpress URL

By default, WordPress category permalinks are displayed that way:

http://www.catswhocode.com/blog/category/wordpress

As you can see, the category in the url is pretty useless. Here's how to remove it:

First backup your .htaccess file. Then, open it and append the following line:

RewriteRule ^category/(.+)$ http://www.yourblog.com/$1 [R=301,L]

Once saved, your categories pages will be displayed like this:

http://www.catswhocode.com/blog/wordpress

Better, isn't it?

Add Private Pages in Navigation Menus

To achieve this recipe, simply open the file where your navigation is (You can look up for the wp_list_pages() function) and insert this snippets instead of the function:

<ul><?phpwp_list_pages('depth=1&title_li=0&sort_column=menu_order');if(current_user_can('read_private_pages')) :?><li><a href="<?php echo get_permalink(10); ?>">For Authors only</a></li><?php endif; ?></ul>

That's all. Your navigation menu now display private pages to specific users.

Create a Logout Link

Page 20: Wordpress Cheats

To create a "Logout" link on your WordPress blog, simply paste the following code on your theme:

<a href="<?php echo wp_logout_url(); ?>">Logout</a>

Please note that this will work with WordPress 2.7+ only. If you haven't switched to WP 2.7 yet, the following code will do (almost) the same job:

<a href="/wp-login.php?action=logout">logout</a>

List of Posts without Tags

To get the list of un-tagged posts, simply paste this custom loop anywhere or your theme, or use a page template. This loop will only show posts that haven't been tagged yet.

<?php query_posts('orderby=title&order=asc&showposts=-1'); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php $tag = get_the_tags(); if (!$tag) { //Theses posts have no tags the_title(); } endwhile; endif; ?>

That's all. Now, you can easily find which posts have no tags yet, and tag them!

Create & use Wordpress Page Templates

Page templates are very useful: They allow you to creates custom pages, for exemple creating an archive page which will list all your posts, or a page to display infos about the author.A page template is defined by the following code, inserted on the firsts lines of the file:

<?php/*Template Name: Archives*/?>

Here, we just created a page template, named "Archives".

Page 21: Wordpress Cheats

To use it on your theme, write a page, and scroll down until you see a "Page Template" dropdown list, as described in the picture below:

Then you just have to choose which page template to use, and save the page.

Create a Tag Page

To create your tag page, the first thing to do is to create a page template. Follow theses simple steps if you don't know how to create one.

Once done, paste the following code in it:

<h2>All tags</h2><?php wp_tag_cloud('number=0'); ?>

That's simple as that! The number=0 parameter specifies that you want to display all tags.

Display latest Delicious Book Mark on the Wordpress Blog

To display your latest Delicious bookmark on your WordPress blog, we'll use WordPress built-in rss parser. To do so we have to include the rss.php file, and then use its wp_rss() function.Of course, don't forget to replace my Delicious bookmarks rss url by yours!

<?php include_once(ABSPATH.WPINC.'/rss.php');wp_rss('http://feeds.delicious.com/v2/rss/jbjweb', 1); ?>

Scroll to Top

Page 22: Wordpress Cheats

First, open header.php and verify that you have a <div id="header"> somewhere. This should be the case on more than 95% of blogs anyways.

Open footer.php (or any other file) and insert the following code where you want your link to appear:

<a href="#header">Scroll to top</a>

Link External resource through Post Title

The first thing to do is to open your functions.php file and paste the following code:

function print_post_title() {global $post;$thePostID = $post->ID;$post_id = get_post($thePostID);$title = $post_id->post_title;$perm = get_permalink($post_id);$post_keys = array(); $post_val = array();$post_keys = get_post_custom_keys($thePostID);

if (!empty($post_keys)) { foreach ($post_keys as $pkey) { if ($pkey=='url1' || $pkey=='title_url' || $pkey=='url_title') { $post_val = get_post_custom_values($pkey); } } if (empty($post_val)) { $link = $perm; } else { $link = $post_val[0]; }

} else { $link = $perm;

}echo '<h2><a href="'.$link.'" rel="bookmark" title="'.

$title.'">'.$title.'</a></h2>';}

Once done, open your index.php file and replace the standard code for printing titles:

<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2>

by a call to our newly created print_post_title() function:

<?php print_post_title() ?>

Page 23: Wordpress Cheats

Now, whenever you feel like let your post title leave your blog and point someplace else, just scroll down in your post writing screen, create or select a custom key named url1 or title_url or url_title and put that external URL in value box.

Authors Gravatar in Posts

To achieve this recipe, simply paste the following code on your single.php file, where you want the gravatar to be displayed:

<?php$author_email = get_the_author_email();echo get_avatar($author_email, '96');

?>

That's easy as that!

Get Thumbnails from Specific Posts

To get a list of thumbnails from the most commented post, we have to use a SQL request and some PHP. Paste the following code anywhere on your theme, where you'd like the thumbnails to be displayed. Each thumbnail contains a link to read the associated post.

<ul><?php

//The name of custom field you'd like to get, don't forget to change it$custom_field_name = "featuredimg";

//Cool sql request$sql = "SELECT p.comment_count, p.ID, m.post_id, m.meta_key, m.meta_valueFROM wp_posts p, wp_postmeta mWHERE p.ID = m.post_idLIMIT 0,10;";

$result = $wpdb->get_results($sql);

foreach ($result as $topten) { $postid = $topten->ID; $title = $topten->post_title; $commentcount = $topten->comment_count; if ( $topten->meta_key == $custom_field_name) { $img = '<img src="'.$topten->meta_value.'" alt=""/>'; ?> <li><a href="<?php echo get_permalink($postid); ?>"><?php echo $img; ?></a></li> <?php }}?></ul>

Page 24: Wordpress Cheats

Once you saved the file, this will work perfectly. Notice that this code get thumbnails from the ten most commented posts, but you can easily modify the number of thumbnails to get: Edit the 0,10 in the sql query, replacing it by 0,3 to get images from the 3 most commented posts.

Display Page List along with description

The first thing to do is to paste the following code where you want your pages to be listed. It can be your sidebar, or a page template, for exemple.

<?php$pages = get_pages(); foreach($pages as $page) { $custom_blurb = get_post_meta($page->ID, 'custom_blurb', true);

echo "<h3><a href=\"".get_page_link($page->ID)."\">$page->post_title</a></h3>";

echo $custom_blurb; }?>

Once you saved your file, write some pages and add the custom_blurb custom field. As a value, give a description of the page.Your pages will now be listed along with a custom description. Nice, isn't it?

Display Last image attached to the Post

First, you have to paste the following code in your functions.php file, in order to create the shortcode.

function sc_postimage($atts, $content = null) {extract(shortcode_atts(array(

"size" => 'thumbnail',"float" => 'none'

), $atts));$images =&

get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );

foreach( $images as $imageID => $imagePost )$fullimage = wp_get_attachment_image($imageID, $size, false);$imagedata = wp_get_attachment_image_src($imageID, $size,

false);$width = ($imagedata[1]+2);$height = ($imagedata[2]+2);return '<div class="postimage" style="width: '.$width.'px;

height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';}add_shortcode("postimage", "sc_postimage");

Page 25: Wordpress Cheats

Once done, you can easily display the last image attached to post by using the postimage shortcode as shown below:

[postimage]

Limit Search to Specific Categories

To achieve this recipe, replace the categories IDs on line 3 and paste the following code on your search.php template:

<?php if( is_search() ) :$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;query_posts("s=$s&paged=$paged&cat=1,2,3");endif; ?>

Display Category Name without Link

To display the category name without haveing a link to the category archive being automatically created, simply open replace the_category( ) by the following code:

<?php$category = get_the_category();echo $category[0]->cat_name;?>

Manually Define to Show Excerpt or Full Post on Home Page

On your index.php file, replace your current loop by this one:

<?php if (have_posts()) : while (have_posts()) : the_post(); $customField = get_post_custom_values("full"); if (isset($customField[0])) { //Custom field is set, display a full post the_title(); the_content(); } else { // No custom field set, let's display an excerpt the_title(); the_excerpt(); endwhile;endif;?>

Page 26: Wordpress Cheats

On the code above, the default is excerpts. When you want to show a full post on your blog homepage, simply edit the post and create a custom field named full and give it any value.

Add new Gravatar to default Gravatar list

Simply paste this code on your functions.php file. Don't forget to change paths to the images in the code.

if ( !function_exists('fb_addgravatar') ) {function fb_addgravatar( $avatar_defaults ) {

$myavatar = get_bloginfo('template_directory').'/images/avatar.gif'; //default avatar

$avatar_defaults[$myavatar] = 'people';

$myavatar2 = get_bloginfo('template_directory').'/images/myavatar.png'; //Avatar for user "admin"

$avatar_defaults[$myavatar2] = 'admin';

return $avatar_defaults;}

add_filter( 'avatar_defaults', 'fb_addgravatar' );}

Disable Search engine Indexing on a particular Category

To achieve, first get the ID of the category you'd like to be not indexed by search engines. In this exemple, I assume your category id is 8.Open your header.php file and paste the following code between the <head> and </head> tags:

<?php if ( is_category('8') || in_category('8') ) { echo '<meta name="robots" content="noindex">';}

That's all. With the above code, we made sure that no post from category with the ID 8 as well as category pages will be indexed by search engines crawlers.

Randomize post order

To randomize posts order, you'll have to use the very powerful query_posts() function before your WordPress loop:

Page 27: Wordpress Cheats

query_posts('orderby=rand');//Your loop goes here

Of course, it is also possible to randomize only a certain category:

query_posts('cat=10&orderby=rand');//Your loop goes here

Display a Text/Code if more than X posts are published

To achieve this recipe, we're going to use a cool new function, introduced in WordPress 2.7, and called wp_count_posts().

Paste the following code anywhere on your template:

<?php$count_posts = wp_count_posts();if ($count_posts->publish > 10) { //Your code to be displayed only if more than ten posts have been published}?>

That's all. Note that you'll need to replace 10 by the number of posts which are displayed at the same time on your homepage.

Define Title tag with a Custom Field

Open your header.php file for edition. find the <title> tag, and replace it by the following code:

<title>

<?php if (is_home () ) { bloginfo('name');} elseif ( is_category() ) { single_cat_title(); echo ' - ' ; bloginfo('name');} elseif (is_single() ) { $customField = get_post_custom_values("title"); if (isset($customField[0])) { echo $customField[0]; } else { single_post_title(); }} elseif (is_page() ) { bloginfo('name'); echo ': '; single_post_title();} else {

Page 28: Wordpress Cheats

wp_title('',true);} ?></title>

Then, if you want to define a custom title tag, simply create a custom field named title, and give your title as a value.

Display Current Mood in Post

Open your single.php file (You can also modify your index.php file) and paste the following code anywhere within the loop:

$customField = get_post_custom_values("mood");if (isset($customField[0])) {echo "Mood: ".$customField[0];

Save the file. Now when you'll write a new post, just create a custom field named mood and type your current mood as a value.

Word Count of a Post

The first thing to do is to create the function. Paste the following code on your functions.php file:

function count_words($str){ $words = 0; $str = eregi_replace(" +", " ", $str); $array = explode(" ", $str); for($i=0;$i < count($array);$i++) { if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i])) $words++; } return $words; }

Then open your single.php file and paste the following code:

Word count: <?php echo count_words($post->post_content); ?>

Display allowed Tags in Comments

To achieve this recipe, edit your comments.php file and paste the following code just above the comment form:

Page 29: Wordpress Cheats

Allowed tags: <?php echo allowed_tags(); ?>

yes, this is as simple as that!

Display Average Comments/Post

Simply paste the following code anywhere on your theme, where you'd like the average comments per post to be displayed:

<?php$count_posts = wp_count_posts();$posts = $count_posts->publish;

$count_comments = get_comment_count();$comments = $count_comments['approved'];

echo "Average ".round($comments/$posts)." comments per post.";?>

This code is quite simple: First, we get the total number of published posts and the total number of approved comments. Once we have it, we just have to divide the number of comments by the number of posts.

Display FeedBurner Count

To display your feedburner count in full text on your WordPress blog, simply paste the following on any of your theme file, for exemple sidebar.php:

<?php$fburl=”https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=YourURL“;$ch = curl_init();curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_URL, $fburl);$stored = curl_exec($ch);curl_close($ch);$grid = new SimpleXMLElement($stored);$rsscount = $grid->feed->entry['circulation'];echo $rsscount;?>

Style Posts Individually

To be able to style posts individually, you have to edit your single.php file and find the line starting with:

<div class="post">

Page 30: Wordpress Cheats

Simply change this line to:

<div class="post" id="post-<?php the_ID(); ?>">

Once you saved the file, you can style an individual post by using the #post-XXX id:

#post-112 { background: #113355; color:#069; font-weight:bold;}

Done! Easy, isn't it?

Number Your Comments

Open comments.php and find the following line:

<?php foreach ($comments as $comment) : ?>

Just above this line, initialize a counter variable:

<?php $i = 0; ?>

Just after this line, increment the counter:

<?php $i++; ?>

Now, you just have to echo the $i variable to get the number of the current comment. Paste this code anywhere on your comments loop:

<?php echo $i; ?>

Your comments are now numbered!

List Future Posts

To achieve this recipe, simply paste this code where you'd like you future posts to be displayed:

<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();

?>

Page 31: Wordpress Cheats

<div ><p class><b><?php the_title(); ?></b><?php

edit_post_link('e',' (',')'); ?><br /><span class="datetime"><?php the_time('j. F

Y'); ?></span></p></div>

<?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?></div>

Display Posts based on Custom Fields with a Custom Query

The code below will display your posts, based on the following condition: Post must have a custom field with key tag and value email. Of course, you can change it in the query to make the code fits your needs

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

$querystr = " SELECT wposts.* FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = 'tag' AND wpostmeta.meta_value = 'email' AND wposts.post_status = 'publish' AND wposts.post_type = 'post' ORDER BY wposts.post_date DESC ";

$pageposts = $wpdb->get_results($querystr, OBJECT);

if ($pageposts): foreach ($pageposts as $post): setup_postdata($post); // Display your post info. For exemple: the_title();the_exerpt(); endforeach;endif;

?>

Happy coding

Page 32: Wordpress Cheats

Get Users of a Specific Role

The first thing to do is to create the function. To do so, paste the following code in your functions.php file:

function getUsersWithRole($role) { $wp_user_search = new WP_User_Search($usersearch, $userspage, $role); return $wp_user_search->get_results();}

Once done, you can call the function this way:

$editors = getUsersWithRole('editor');foreach($editors as $editor){ //$editor now holds the user ID of an editor}

Line Breaks between widgets

To add a line break between sidebar widgets, simply open your style.css file and append the following code:

.widget{ margin-bottom:25px;}

Easy, isn't it? Note that it is possible to add a linre break to a specific widget only. You'll need its css id for that.

Get first Image from the Post & Display

First, paste this function on your functions.php file.

function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image $first_img = "/images/default.jpg"; } return $first_img;}

Page 33: Wordpress Cheats

Once done, you can simply call the function within the loop to display the first image from the post:

<?php echo catch_that_image() ?>

Disable “Please Update Now” link in wordpress

To get rid of the "Please update now" message in your WordPress dashboard, simply paste the following code on your functions.php file.

if ( !current_user_can( 'edit_users' ) ) { add_action( 'init', create_function( '$a', "remove_action( 'init', 'wp_version_check' );" ), 2 ); add_filter( 'pre_option_update_core', create_function( '$a', "return null;" ) );}

Display the Most Popular content in the Sidebar

Just paste the following code on your sidebar.php file. To change the number of displayed posts, simply change the 5 on line 3.

<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 , 5");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>

Related Posts

This code will display related posts based on the current post tag(s). It must be pasted within the loop.

<?php//for use in the loop, list 5 post titles related to first tag on current post$tags = wp_get_post_tags($post->ID);

Page 34: Wordpress Cheats

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'=>5, '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; }}?>

Avoid Duplicate Content

Simply paste theses line between the <head> and </head> tags in your header.php file.

<?php if((is_home() && ($paged < 2 )) || is_single() || is_page() || is_category()){ echo '<meta name="robots" content="index,follow" />';} else { echo '<meta name="robots" content="noindex,follow" />';}

By using WordPress conditionnal tags, this code ensure that your homepage, posts, pages and category pages are indexed by search engines spiders, but prevent all other pages (feeds, archives, etc) from being indexed and create involuntary duplicate content.

Suggest Visitors to leave Comments in RSS feeds

Additionally, when using WordPress as CMS, sometimes it is necessary to create new posts instead of pages for static pages because you want them to appear in the RSS feed. You may not want to enable comments inside those posts.

At other cases, you may also want to selectively choose to enable and disable comments. The problem is, how do you prevent your RSS feed subscribers from clicking with the intention to leave comment while the comment is disabled?

How about giving them a clue at the end of the post? To achieve this recipe, just put the following code in the functions.php file within your active theme:

function rss_comment_footer( $content ) { if ( is_feed() ) {

Page 35: Wordpress Cheats

if ( comments_open() ) { $content .= "\n\nComment is open. You can participate in the discussionby visiting <a href='".get_permalink()."'>here</a>\n"; } } return $content;}

Get Rid of Links in Comments

Just paste this code in your function.php file. Once the file is saved, you can say goodbye to links and other undesired html in your comments.

function plc_comment_post( $incoming_comment ) {$incoming_comment['comment_content'] =

htmlspecialchars($incoming_comment['comment_content']);$incoming_comment['comment_content'] = str_replace( "'",

'&apos;', $incoming_comment['comment_content'] );return( $incoming_comment );

}

function plc_comment_display( $comment_to_display ) {$comment_to_display = str_replace( '&apos;', "'",

$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);

Manually Reset WP Password

UPDATE 'wp_users' SET 'user_pass' = MD5('PASSWORD') WHERE 'user_login' ='admin' LIMIT 1;

Automatically Provide Tiny URLs in Wordpress Blogs

To achieve this recipe, simply open your functions.php file and paste the following code:

function getTinyUrl($url) { $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url); return $tinyurl;}

Page 36: Wordpress Cheats

On your single.php file, paste the following within the loop:

<?php$turl = getTinyUrl(get_permalink($post->ID));echo 'Tiny Url for this post: <a href="'.$turl.'">'.$turl.'</a>'?>

Remove Widgets from Homepage without editing Template Files

To do so, simply add the following code to your functions.php file:

<?phpadd_filter( 'sidebars_widgets', 'disable_all_widgets' );

function disable_all_widgets( $sidebars_widgets ) {if ( is_home() )

$sidebars_widgets = array( false );return $sidebars_widgets;

}?>

Avoid duplicate content in paged comments

Open your header.php file. Find the </title> tag and paste the following just above:

<?php if ( $cpage < 2 ) {}else { echo (' - comment page '); echo ($cpage);}?>

Allright, after you saved the file you can say goodbye to duplicate content!

Force using SSL on wp-admin directory

What is SSL? According to Wikipedia:"SSL is a cryptographic protocol that provide security and data integrity for communications over TCP/IP networks such as the Internet. TLS and SSL encrypt the segments of network connections at the Transport Layer end-to-end."In other words, SSL can secure transactions over the internet.

Not all hosting services allows you to use SSL. Though, if you're hosted on Wp WebHost or HostGator, then SSL is enabled.

Once you checked that your webserver can handle SSL, opne your wp-config.php file (Located at the root of your WordPress install) and paste the following:

Page 37: Wordpress Cheats

define('FORCE_SSL_ADMIN', true);

Save the file, and you're done!

Display Number of Results in wp-Search

Open your search template file, search.php. In it, search for the following:

<h2 class="pagetitle">Search Results</h2>

Now replace this with:

<h2 class="pagetitle">Search Results for <?php /* Search Count */ $allsearch = &new WP_Query("s=$s&showposts=-1"); $key = wp_specialchars($s, 1); $count = $allsearch->post_count; _e(''); _e('<span class="search-terms">'); echo $key; _e('</span>'); _e(' — '); echo $count . ' '; _e('articles'); wp_reset_query(); ?></h2>

That's all, you're done!

Share a Facebook Link

Simply paste the following code on your single.php file, within the loop:

<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>" target="blank">Share on Facebook</a>

That's all. Your readers are now able to send your blog post on Facebook and share it with their friends!

Remove the […] from the excerpt

To get rid of the [...] at the end of the post excerpt, simply paste the following function in the functions.php file from your theme:

function trim_excerpt($text) { return rtrim($text,'[...]');}add_filter('get_the_excerpt', 'trim_excerpt');

Insert Special Char’s between menu Items

Page 38: Wordpress Cheats

To apply this hack, simply paste the following code where you want your menu to be displayed.

<?php$char = ' \\ ';wp_list_pages('link_before=<li>&link_after='.$char.'</li>');?>

Get Latest Sticky Posts

To achieve this recipe, place the following code just before the loop:

<?php$sticky = get_option('sticky_posts');rsort( $sticky );$sticky = array_slice( $sticky, 0, 5);

query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) );?>

This code will retrieve the 5 most recent sticky posts. To change the number of retrieved posts, just change the 5 by the desired value on line 4.

List the Most Recent Comments

To use this hack, simply paste this code anywhere on your theme files.

<?php global $wpdb; $sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,30) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 10";

$comments = $wpdb->get_results($sql); $output = $pre_HTML; $output .= "\n<ul>"; foreach ($comments as $comment) { $output .= "\n<li>".strip_tags($comment->comment_author) .":" . "<a href=\"" . get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "\" title=\"on ".$comment->post_title . "\">" . strip_tags($comment->com_excerpt)."</a></li>"; } $output .= "\n</ul>"; $output .= $post_HTML; echo $output;?>

Page 39: Wordpress Cheats

This code will list the 10 most recent comments. If you want to list more or less comments, simply change the "10" in the $sql variable.

Automatically insert Content after each post

To achieve this recipe, simply paste the following code in your functions.php file. By using functions.php, you'll not have to re-insert this code if you switch themes.

function insertFootNote($content) { if(!is_feed() && !is_home()) { $content.= "<div class='subscribe'>"; $content.= "<h4>Enjoyed this article?</h4>"; $content.= "<p>Subscribe to our <a href='http://feeds2.feedburner.com/WpRecipes'>RSS feed</a> and never miss a recipe!</p>"; $content.= "</div>"; } return $content;}add_filter ('the_content', 'insertFootNote');

Prevent Post Images from getting displayed in the Home Page

Simply paste this code in your functions.php file:

<?phpadd_filter('the_content','wpi_image_content_filter',11);

function wpi_image_content_filter($content){

if (is_home() || is_front_page()){ $content = preg_replace("/<img[^>]+\>/i", "", $content); }

return $content;}?>

Article to Email a Friend

To achieve this recipe, simply open your single.php template and paste the following code within the loop, where you want the "Email this" link to be displayed:

<a href="mailto:?subject=<?php the_title();?>&amp;body=<?php the_permalink() ?>" title="Send thisarticle to a friend!">Email this</a>

Wordpress shortcode to display related posts

Page 40: Wordpress Cheats

To create the shortcode, simply open your functions.php file and paste the shortcode function:

function related_posts_shortcode( $atts ) {extract(shortcode_atts(array( 'limit' => '5',), $atts));

global $wpdb, $post, $table_prefix;

if ($post->ID) {$retval = '<ul>';

// Get tags$tags = wp_get_post_tags($post->ID);$tagsarray = array();foreach ($tags as $tag) {

$tagsarray[] = $tag->term_id;}$tagslist = implode(',', $tagsarray);

// Do the query$q = "SELECT p.*, count(tr.object_id) as count

FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy ='post_tag' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID

AND p.post_status = 'publish'AND p.post_date_gmt < NOW()

GROUP BY tr.object_idORDER BY count DESC, p.post_date_gmt DESCLIMIT $limit;";

$related = $wpdb->get_results($q); if ( $related ) {

foreach($related as $r) {$retval .= '

<li><a title="'.wptexturize($r->post_title).'" href="'.get_permalink($r->ID).'">'.wptexturize($r->post_title).'</a></li>';

}} else {

$retval .= '<li>No related posts found</li>

';}$retval .= '</ul>

';return $retval;

}return;

}add_shortcode('related_posts', 'related_posts_shortcode');

Page 41: Wordpress Cheats

Once done, you can use the following shortcode in your posts to display the related content:

[related_posts]

Display total users of Wordpress Blog

To achieve this recipe, simply paste the following code anywhere in your theme files:

$users = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users");echo $users." registered users.";

Once you saved the file and refreshed your blog, the total number of users will be displayed.

Get Trim URL’s for the Blog

The first thing to do is to add the following function to your functions.php file:

function getTrimUrl($url) { $tinyurl = file_get_contents("http://api.tr.im/api/trim_simple?url=".$url); return $tinyurl;}

On your single.php file, paste the following within the loop:

<?php$turl = getTrimUrl(get_permalink($post->ID));echo 'Short Url for this post: <a href="'.$turl.'">'.$turl.'</a>'?>

That's all, enjoy tr.im urls!

Display total number of Twitter Followers in Blog

The first thing to do is to paste the following php functions on the functions.php file from your WordPress blog theme:

function string_getInsertedString($long_string,$short_string,$is_html=false){ if($short_string>=strlen($long_string))return false; $insertion_length=strlen($long_string)-strlen($short_string); for($i=0;$i<strlen($short_string);++$i){ if($long_string[$i]!=$short_string[$i])break; }

Page 42: Wordpress Cheats

$inserted_string=substr($long_string,$i,$insertion_length); if($is_html && $inserted_string[$insertion_length-1]=='<'){ $inserted_string='<'.substr($inserted_string,0,$insertion_length-1); } return $inserted_string;}

function DOMElement_getOuterHTML($document,$element){ $html=$document->saveHTML(); $element->parentNode->removeChild($element); $html2=$document->saveHTML(); return string_getInsertedString($html,$html2,true);}

function getFollowers($username){ $x = file_get_contents("http://twitter.com/".$username); $doc = new DomDocument; @$doc->loadHTML($x); $ele = $doc->getElementById('follower_count'); $innerHTML=preg_replace('/^<[^>]*>(.*)<[^>]*>$/',"\\1",DOMElement_getOuterHTML($doc,$ele)); return $innerHTML;}

Then, simply paste the following anywhere on your theme files. Just replace my username with yours.

<?php echo getFollowers("catswhocode")." followers"; ?>

Display Latest Author who modified a Post

To create the function, just paste the code below in your functions.php file:

if (!function_exists('get_the_modified_author')) { function get_the_modified_author() { global $post; if ( $last_id = get_post_meta($post->ID, '_edit_last', true) ) { $last_user = get_userdata($last_id); return apply_filters('the_modified_author', $last_user->display_name); } }}

if (!function_exists('the_modified_author')) { function the_modified_author() { echo get_the_modified_author(); }}

Page 43: Wordpress Cheats

Once you saved the file, you can display the name of the latest author who modified the post by using this code:

<?php the_modified_author(); ?>

Automatically Insert Text in the Wordpress Editor

Really simple: Just open your functions.php file, and paste the following code:

<?phpadd_filter( 'default_content', 'my_editor_content' );

function my_editor_content( $content ) {$content = "If you enjoyed this post, make sure to subscribe to

my rss feed.";return $content;

}?>

Save the file, and create a new post: The "If you enjoyed this post, make sure to subscribe to my rss feed." text is already in WordPress editor!

Display Posts in Column

To split your post content in columns, the first thing to do is to format your posts that way:

potential content goes here that appears before the columns.[--column--]Content for column 1 here.[--column--]Content for column 2 here.[--column--]Content for column 3 here.

Once done, open your single.php file and the following code within the loop:

<?php$page_columns = explode("[--column--]", $post->post_content);print $page_columns[0];print '<div class="column first">';print $page_columns[1];print '</div>';print'<div class="column second">';print $page_columns[2];print '</div>';print '<div class="column third">';print $page_columns[3];print '</div>';?>

The last part is css styling. Open your style.css file and paste the styles below in it:

Page 44: Wordpress Cheats

.column{ width:33%; float:left; margin-right:10px;}

column.first, column.second, column.third, { /* Customize to fit your needs */}

That's all, you can finally display your posts in three columns!

Display content to registered users

Just paste the following code on your functions.php file:

add_shortcode( 'member', 'member_check_shortcode' );

function member_check_shortcode( $atts, $content = null ) { if ( is_user_logged_in() && !is_null( $content ) && !

is_feed() )return $content;

return '';}

Once done, you can add the following to your posts to create a portion or text (or any other content) that will be only displayed to registered users:

[member]This text will be only displayed to registered users.[/member]

That's all. Easy and useful!

Display posts between 2 dates

Open your index.php file and find the loop. Just before the loop starts, paste the following code. Of course, don't forget to change the dates on line 3 according to your needs.

<?php function filter_where($where = '') { $where .= " AND post_date >= '2009-05-01' AND post_date <= '2009-05-15'"; return $where; }add_filter('posts_where', 'filter_where');query_posts($query_string);

Page 45: Wordpress Cheats

?>

Display today’s date

Open your header.php file (or any other file) and paste the following code:

<?php echo date('l jS F Y'); ?>

The date format can be easily formatted

RSS feeds for several tags on WPress Blog

Simply paste this code wherever you'd like your custom RSS feed to be displayed:

<a href="http://wprecipes.com/?feed=rss&tag=query_posts,loop">

As you can see, the list of tags are separated by a comma. Change the tags in the exemple to fit your needs, and you're done!

Get post with a specific Custom Field/Value pair

To achieve this recipe, simply find the loop and add the query_posts() function just above, as in the example below:

<?php query_posts('meta_key=review_type&meta_value=movie'); ?><?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>

You'll get the list of post having review_type as a custom field key and movie as a value. Just change theses values to fit your needs.

Get Short URL’s for Social Bookmarking

This hack is very simple. Instead of using permalinks, let's use the post ID to get a shorter url.

Paste the following code on your single.php file:

<?php echo get_bloginfo('url')."/?p=".$post->ID; ?>

It will output an url of this form:

Page 46: Wordpress Cheats

http://www.wprecipes.com/?p=54

And you're reading for twitter sharing!

Number of Tweets in Text Mode in Wordpress Blog

paste the following function in your functions.php file:

<?phpfunction tweets($url){ $content = file_get_contents("http://api.tweetmeme.com/url_info?url=".$url); $x = new SimpleXmlElement($content); $tweets = $x->story->url_count; echo "Tweets: ".$tweets;}

Once done, you can get the number of tweets for any web page you want, for exemple:

<?php tweets("http://www.wprecipes.com"); ?>

To automatically display how many times your posts has been tweet, open the single.php file file and paste the following code:

<?php tweets($post->permalink); ?>

Display Tags in Drop Down

The first thing to do is to create the function. Paste the following code to your functions.php file:

<?phpfunction 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

Page 47: Wordpress Cheats

if ( is_wp_error( $return ) )return false;

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

elseasort($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]);

Page 48: Wordpress Cheats

$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 done, you can use the function 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'); ?>

Hide portion of text to Google

Hiding a portion of text to Google is damn easy, but not everyone is aware of this method. Simply use the following html comments in your source files (or in WordPress editor, in html mode) to hide a specific sentence or text to Google robots.

This text will be indexed by Google...<!--googleoff: all--> ...but not that one! <!--googleon: all>

That's all. These tags tells Google that the text embeded within them should not be indexed. Of course, you can use it on your theme files, posts and non-WordPress websites/webpages.

Rid of Auto Media Enclosures

Page 49: Wordpress Cheats

Just paste the following lines of codes within your functions.php file, and then, say goodby to automatic enclosures!

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

Prevent Wpress Style Sheet from being Cached

To get rid of browser caching on your stylesheet, just edit your header.php file, and use the code below to include your stylesheet:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?'.filemtime( get_stylesheet_directory().'/style.css'); ?>" type="text/css" media="screen, projection" />

Create Invisible Custom Fields

This little trick is extremely simple: All you have to do is give a name starting with an underscore to your custom field when you create it, and it will not be displayed on WordPress dashboard when editing a post, as shown in the example below:

add_post_meta($id, '_name', 'value');

Display Categories in 2 Columns

Simply paste the following piece of code where you'd like your categories to be displayed:

<?php$cats = explode("<br />",wp_list_categories('title_li=&echo=0&depth=1&style=none'));$cat_n = count($cats) - 1;for ($i=0;$i<$cat_n;$i++):if ($i<$cat_n/2):$cat_left = $cat_left.'<li>'.$cats[$i].'</li>';elseif ($i>=$cat_n/2):$cat_right = $cat_right.'<li>'.$cats[$i].'</li>';endif;endfor;?><ul class="left"><?php echo $cat_left;?></ul><ul class="right"><?php echo $cat_right;?>

Page 50: Wordpress Cheats

</ul>

Then, just save the file, and enjoy!

Add Private notes to your Wordpress Blog Posts

Here's the code you need to add to your functions.php file:

add_shortcode( 'note', 'sc_note' );

function sc_note( $atts, $content = null ) { if ( current_user_can( 'publish_posts' ) )

return '<div class="note">'.$content.'</div>';return '';

}

Once done, simply add the following shortcode in your posts:

[note]This is a personal note that only admins can see![/note]

Note that the note will be displayed with a <div class="note"></div> tags, so you can use it to give a specific style to your notes!

Disable Automatic Formatting

The first thing to do is to add the following function to your functions.php file:

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

Page 51: Wordpress Cheats

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

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

[raw]Unformatted code[/raw]

Custom Read More link

To achieve this recipe, 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); ?>

That's all. Now, if you create a custom field named custom_more, its value will be displayed instead of the classic "Read more" link.

Prevent Images from Being too large

Simply paste the following in your style.css file:

.post img { max-width: 500px; /* Adjust this value according to your content area size*/ height: auto;}

Most WordPress themes display posts content within a <div class="post"> tag. However, if the hack don't work, make sure you have this tag on your single.php file.

Wordpress Page template to redirect to first child page

To achieve this recipe, you have to create a page template. Create a new file and paste the following code in it:

Page 52: Wordpress Cheats

<?php/*Template Name: Redirect To First Child*/if (have_posts()) { while (have_posts()) { the_post(); $pagekids = get_pages("child_of=".$post->ID."&sort_column=menu_order"); $firstchild = $pagekids[0]; wp_redirect(get_permalink($firstchild->ID)); }}?>

Save the file under the name redirect.php and upload it to the wp-content/themes/your-theme directory of your WordPress install. Once done, you can use the page template.

Get Custom fields outside the loop

To display a custom field value outside the loop, simply use the following code. Don't forget to replace customField on line 4 by the name of the custom field you want to display.

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

Attachments in Posts

$args = array('post_type' => 'attachment','numberposts' => null,'post_status' => null,'post_parent' => $post->ID

);$attachments = get_posts($args);if ($attachments) {

foreach ($attachments as $attachment) {echo apply_filters('the_title', $attachment-

>post_title);the_attachment_link($attachment->ID, false);

}}

Page 53: Wordpress Cheats