Professional Documents
Culture Documents
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.
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(); ?>
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');
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.
This recipe is very easy to achieve: Paste the following code within the loop, on your
single.php file.
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.
<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>
Open your header.php file. Paste the following code anywhere within the <head> and
</head> tags:
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
} ?>
To achieve this recipe, edit your index.php file and look for the loop. Replace it with that
one:
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 */
}
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');
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 title
echo $data[0]->post_date; //Print post date
echo $data[0]->comment_count; //Print number of comments
echo $data[0]->post_content; /Print post content
?>
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');
That's all, authors are now allowed to use html in their profiles!
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.
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).
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 On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{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.
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!
To create a 301 redirection within WordPress, you just have to add the 301 argument to
the function:
To achieve this recipe, you first have to creat the function which will takes your post
content, clean it and print or return it.
Copy the code below to the functions.php file from your theme. Create that file if it
doesn't exists.
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).
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:
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() {
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.
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:
You can also use this function with the $post global variable:
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.
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.
When you're writing a post/page, insert the following code in the html editor:
To achieve this recipe, simply open your index.php file and paste the following code
within the loop:
Even better, this simple line of code have a link to jump directly to the comments:
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.
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.
<?php
function 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!
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]
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.
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 />
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>
<?php
query_posts("showposts=50");
while (have_posts()) : the_post();
if (!in_array($post->ID, $ids)) {
the_title();?>
<br />
<?php }
endwhile; ?>
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');
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;
?>
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
$szPostContent = $post->post_content;
$szSearchPattern = '~<img [^\>]*\ />~';
// Run preg_match_all to grab all the images and save the results in
$aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );
// 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;
?>
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;
?>
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.
<?php
if ((date('m') == 12) && (date('d') == 25)) { ?>
<h2>Merry Christmas from WpRecipes!</h2>
<?php } ?>
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 if (!is_front_page()) {
get_sidebar();
} ?>
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.
When you're browsing a category, WordPress automatically add a current-cat css class to
the <li> element.
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;
}
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!
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');
// 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_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.
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 */
}
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:
To achieve this recipe, simply paste the following code on he sidebar.php file of your
theme:
<?php
query_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.
To achieve this recipe, simply paste the following line of code on the functions.php file
from your theme.
remove_filter('comment_text', 'wptexturize');
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();
} ?>
You can also use that new functionality with footers and sidebars:
Open your search.php file and find the the_title() function. Replace it with the following:
echo $title;
<?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:
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:
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:
http://www.catswhocode.com/blog/wordpress
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>
<?php
wp_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.
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>
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.
That's all. Now, you can easily find which posts have no tags yet, and tag them!
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
*/
?>
Then you just have to choose which page template to use, and save the 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.
<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.
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
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:
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:
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');
?>
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";
$result = $wpdb->get_results($sql);
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?
First, you have to paste the following code in your functions.php file, in order to create
the shortcode.
[postimage]
To achieve this recipe, replace the categories IDs on line 3 and paste the following code
on your search.php template:
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;
?>
<?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;
?>
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.
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;
}
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:
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.
To randomize posts order, you'll have to use the very powerful query_posts() function
before your WordPress loop:
query_posts('orderby=rand');
//Your loop goes here
query_posts('cat=10&orderby=rand');
//Your loop goes here
To achieve this recipe, we're going to use a cool new function, introduced in WordPress
2.7, and called wp_count_posts().
<?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.
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 {
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.
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.
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:
To achieve this recipe, edit your comments.php file and paste the following code just
above the comment form:
Allowed tags: <?php echo allowed_tags(); ?>
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'];
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.
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;
?>
To be able to style posts individually, you have to edit your single.php file and find the
line starting with:
<div class="post">
Simply change this line to:
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;
}
<?php $i = 0; ?>
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:
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();
?>
<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>
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
";
if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
// Display your post info. For exemple: the_title();the_exerpt();
endforeach;
endif;
?>
Happy coding
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();
}
$editors = getUsersWithRole('editor');
foreach($editors as $editor){
//$editor now holds the user ID of an editor
}
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.
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];
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;" ) );
}
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);
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.
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.
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:
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.
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;
}
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>'
?>
<?php
add_filter( 'sidebars_widgets', 'disable_all_widgets' );
Open your header.php file. Find the </title> tag and paste the following just above:
Allright, after you saved the file you can say goodbye to duplicate content!
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:
define('FORCE_SSL_ADMIN', true);
Open your search template file, search.php. In it, search for the following:
Simply paste the following code on your single.php file, within the loop:
That's all. Your readers are now able to send your blog post on Facebook and share it
with their friends!
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');
<?php
$char = ' \\ ';
wp_list_pages('link_before=<li>&link_after='.$char.'</li>');
?>
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.
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;
?>
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.
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');
<?php
add_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;
}
?>
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:
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_id
ORDER BY count DESC, p.post_date_gmt DESC
LIMIT $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');
Once done, you can use the following shortcode in your posts to display the related
content:
[related_posts]
To achieve this recipe, simply paste the following code anywhere in your theme files:
Once you saved the file and refreshed your blog, the total number of users will be
displayed.
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;
}
<?php
$turl = getTrimUrl(get_permalink($post->ID));
echo 'Short Url for this post: <a href="'.$turl.'">'.$turl.'</a>'
?>
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;
}
$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_get
OuterHTML($doc,$ele));
return $innerHTML;
}
Then, simply paste the following anywhere on your theme files. Just replace my
username with yours.
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();
}
}
Once you saved the file, you can display the name of the latest author who modified the
post by using this code:
Really simple: Just open your functions.php file, and paste the following code:
<?php
add_filter( 'default_content', 'my_editor_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!
To split your post content in columns, the first thing to do is to format your posts that
way:
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:
.column{
width:33%;
float:left;
margin-right:10px;
}
That's all, you can finally display your posts in three columns!
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]
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);
?>
Open your header.php file (or any other file) and paste the following code:
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!
To achieve this recipe, simply find the loop and add the query_posts() function just
above, as in the example below:
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.
This hack is very simple. Instead of using permalinks, let's use the post ID to get a shorter
url.
<?php
function 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:
To automatically display how many times your posts has been tweet, open the single.php
file file and paste the following code:
The first thing to do is to create the function. Paste the following code to your
functions.php file:
<?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 );
if ( empty($tags) )
return;
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;
if ( 'DESC' == $order )
$counts = array_reverse( $counts, true );
$a = array();
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;
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'); ?>
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.
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.
function delete_enclosure(){
return '';
}
add_filter( 'get_enclosed', 'delete_enclosure' );
add_filter( 'rss_enclosure', 'delete_enclosure' );
add_filter( 'atom_enclosure', 'delete_enclosure' );
To get rid of browser caching on your stylesheet, just edit your header.php file, and use
the code below to include your stylesheet:
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:
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;?>
</ul>
[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!
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);
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]
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");
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.
.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.
To achieve this recipe, you have to create a page template. Create a new file and paste the
following code in it:
<?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.
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.
<?php
global $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);
}
}