WordPress hack: Automatically add post name to the body class

The only thing you have to do is to copy the following function and paste it on your theme functions.php file. Once saved, the post/page name will be automatically be added to the body class.

function wpprogrammer_post_name_in_body_class( $classes ){
	if( is_singular() )
	{
		global $post;
		array_push( $classes, "{$post->post_type}-{$post->post_name}" );
	}
	return $classes;
}

add_filter( 'body_class', 'wpprogrammer_post_name_in_body_class' );

Thanks to Utkarsh Kukreti for this great hack!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress hack: Automatically add post name to the body class

WordPress hack: Get rid of HTML in comments

Just paste the code below into your functions.php file. If you prefer to use a plugin with the same functionality, you can grab one here.

// This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {

	// convert everything in a comment to display literally
	$incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);

	// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
	$incoming_comment['comment_content'] = str_replace( "'", ''', $incoming_comment['comment_content'] );

	return( $incoming_comment );
}

// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {

	// Put the single quotes back in
	$comment_to_display = str_replace( ''', "'", $comment_to_display );

	return $comment_to_display;
}

add_filter( 'preprocess_comment', 'plc_comment_post', '', 1);
add_filter( 'comment_text', 'plc_comment_display', '', 1);
add_filter( 'comment_text_rss', 'plc_comment_display', '', 1);
add_filter( 'comment_excerpt', 'plc_comment_display', '', 1);

Thanks to Peter’s useful crap for this nice code!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress hack: Get rid of HTML in comments

How to easily enable/disable debug mode in WordPress

The first thing to do is to add the following code to your wp-config.php file. This file is located at the root of your WordPress install.

if ( isset($_GET['debug']) && $_GET['debug'] == 'debug')
  define('WP_DEBUG', true);

Once done, simply add a GET parameter to the url of the page you’d like to debug, as shown below:

http://www.wprecipes.com/contact?debug=debug

Thanks to Joost de Valk for this great tip!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

How to easily enable/disable debug mode in WordPress

How to easily create charts using jQuery and HTML5

Step 1: Preparing files

Here we go! The first thing to do is obviously to create a directory on your Mac (or PC, nobody’s perfect ;) ). You should name it chart for example. Once done, download the required Javascript and CSS files and save it on your hard drive.

Now, create a new html document, named charts.html. Copy the html structure below, and paste it into your newly created charts.html file.

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
	<title>Charts!</table>       

</head>

<body>

</body>
</html>

Did you notice that I used the <!DOCTYPE html> doctype? It is the right doctype to use, as the javscript code we’ll add later will turn a html table into a HTML 5 canvas.

Step 2: Adding data

Now that we downloaded the javascript files and created an html document, it’s time to add data. Copy the code below and paste it within the <body> and </body> tags of your charts.html file.

<table>
	<caption>Visits from August 16 to August 21</caption>
	<thead>
		<tr>
			<td></td>
			<th scope="col">Monday</th>
			<th scope="col">Tuesday</th>
			<th scope="col">Wednesday</th>
			<th scope="col">Thursday</th>
			<th scope="col">Friday</th>
			<th scope="col">Saturday</th>
			<th scope="col">Sunday</th>
		</tr>
	</thead>
	<tbody>

		<tr>
			<th scope="row">CatsWhoCode.com</th>
			<td>12541</td>
			<td>11204</td>
			<td>11354</td>
			<td>10058</td>
			<td>9871</td>
			<td>8254</td>
			<td>5477</td>
		</tr>
		<tr>
			<th scope="row">WpRecipes.com</th>
			<td>9855</td>
			<td>8870</td>
			<td>8731</td>
			<td>7488</td>
			<td>8159</td>
			<td>6547</td>
			<td>4512</td>
		</tr>
		<tr>
			<th scope="row">CatsWhoBlog.com</th>
			<td>3241</td>
			<td>2544</td>
			<td>2597</td>
			<td>3108</td>
			<td>2114</td>
			<td>2045</td>
			<td>950</td>
		</tr>
	</tbody>
</table>

Of course, feel free to add your own data to make the example more interesting for you.

Step 3: Let the magic happen

Alright, now we have a bunch of downloaded files and an html document. It’s time to merge them all together and finally generate the chart.
Unzip the downloaded file and open the extracted directory. Copy the following files into your chart directory.

  • charting/css/basic.css
  • charting/css/visualize.css
  • charting/css/visualize-light.css
  • charting/js/visualize.js

Once done, we obviously have to link the css and javascript files to our document. Paste the following after the <title> tag of the document:

<link href="basic.css" type="text/css" rel="stylesheet" />
<link href="visualize.css" type="text/css" rel="stylesheet" />
<link href="visualize-light.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="visualize.js"></script>

It’s time to give life to our chart. Paste the final piece of code after the script calls:

<script type="text/javascript">
	$(function(){
		$('table').visualize();
	});
</script>

Once you saved the file, your HTML table should be displayed along with a good looking chart. If you don’t want the table to be visible, simply hide it using the display:none css property.

Additional explanations

Generating bar charts is definitely great, but what if your preference goes to a pie chart? No problem, visualize.js allows 4 different type of charts: Bar, area, pie and line.

Changing the default type is pretty easy: Just add the type parameter as shown below:

$('table').visualize({type: 'pie'});

Cool, isn’t it? Visualize.js accepts even more parameters to make sure your chart will look exactly how you want. Here are the parameters which can be used:

  • type: string. Accepts ‘bar’, ‘area’, ‘pie’, ‘line’. Default: ‘bar’.
  • width: number. Width of chart. Defaults to table width
  • height: number. Height of chart. Defaults to table height
  • appendTitle: boolean. Add title to chart. Default: true.
  • title: string. Title for chart. Defaults to text of table’s Caption element.
  • appendKey: boolean. Adds the color key to the chart. Default: true.
  • colors: array. Array items are hex values, used in order of appearance. Default: [‘#be1e2d’,’#666699′,’#92d5ea’,’#ee8310′,’#8d10ee’,’#5a3b16′,’#26a4ed’,’#f45a90′,’#e9e744′]
  • textColors: array. Array items are hex values. Each item corresponds with colors array. null/undefined items will fall back to CSS text color. Default: [].
  • parseDirection: string. Direction to parse the table data. Accepts ‘x’ and ‘y’. Default: ‘x’.
  • pieMargin: number. Space around outer circle of Pie chart. Default: 20.
  • pieLabelPos: string. Position of text labels in Pie chart. Accepts ‘inside’ and ‘outside’. Default: ‘inside’.
  • lineWeight: number. Stroke weight for lines in line and area charts. Default: 4.
  • barGroupMargin: number. Space around each group of bars in a bar chart. Default: 10.
  • barMargin: number. Creates space around bars in bar chart (added to both sides of each bar). Default: 1

That’s all for today. Have fun with the charts :)

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

How to easily create charts using jQuery and HTML5

Add a Facebook “Like” button to your WordPress blog

Open your single.php (or any file where you’d like the “Like” button to be displayed), and paste the following code:

<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo urlencode(get_permalink($post->ID)); ?>&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:450px; height:25px"></iframe>

That’s all. Once the file saved, the facebook “Like” button will be displayed. A live demo can be seen on Visiter New York.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

Add a Facebook “Like” button to your WordPress blog

8 examples of stunning CSS3 text effects

How to Create Inset Typography with CSS3


Just two years ago, we all used Photoshop to create beautiful inset typography. Now, you can do it using only CSS3. This great tutorial will help you getting started.
View tutorial: http://sixrevisions.com/css/how-to-create-inset-typography-with-css3/

Create Beautiful CSS3 Typography


Technically speaking, styling text is very simple. The hard part is the artistic part: How to make text easy to read and look good? This is the focus of the tutorial, which is a must read for all web developers and designers.
View tutorial: http://blog.echoenduring.com/2010/05/13/create-beautiful-css3-typography/

Create a Letterpress Effect with CSS Text-Shadow


The “letterpress” effect is very popular in web design. Many people do it using Photoshop, but you can do it extremely easily using CSS3 only. How? Chris Spooner shows you how in this interesting article.
View tutorial: http://line25.com/tutorials/create-a-letterpress-effect-with-css-text-shadow

How to Create a Cool Anaglyphic Text Effect with CSS


Chris Spooner again! This time, the talented British web designer comes back with a tutorial showing you how you can create a anaglyphic effect with CSS. Not sure I’ll use it on a live site, but it’s always interesting to know how to do it.
View tutorial: http://line25.com/tutorials/how-to-create-a-cool-anaglyphic-text-effect-with-css

Text Rotation with CSS


Why should text always be displayed horizontally? CSS3 has the transform: rotate property, which allow you to rotate any elements, including text. The following tutorial, written by Jonathan Snook, will show how in details how to achieve an awesome rotated text effect.
View tutorial: http://snook.ca/archives/html_and_css/css-text-rotation

Text Embossing Technique With CSS


One more technique I’ve done exclusively in photoshop in the past. Thanks to CSS3, I’m now able to do it entirely in CSS.
View tutorial: http://www.reynoldsftw.com/2009/03/text-embossing-technique-with-css/

Adding an outline to your text using the CSS3 text-stroke property


Although this technique only works in webkit for now, I must admit that I really love it. You can add an outline to text, and even better, use transparent text with a solid outline.
View tutorial: http://www.cardeo.ca/2010/adding-an-outline-to-your-text-using-the-css3-text-stroke-property

CSS textured text


Ok, this isn’t new, and this isn’t CSS3, but this example is so great that I can’t not feature it on this post. Nick La from WebDesignerWall explains how you can make gradients or textured texts using CSS.
View tutorial: http://www.webdesignerwall.com/tutorials/css-gradient-text-effect/

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

8 examples of stunning CSS3 text effects

WordPress tip: Close trackbacks on all posts at once

Simply run the following SQL query on your WordPress database, using the command line client or PhpMyAdmin. This will close pingbacks/trackbacks on all existing posts.
Don’t forget to backup your database before using this query.

UPDATE wp_posts SET ping_status = 'closed';

If you like to know more about WordPress SQL queries, you should have a look to this article.

Thanks to Jeff Starr for this nice piece of code!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress tip: Close trackbacks on all posts at once

8 CSS preprocessors to speed up development time

Less CSS

Less is probably the most well known CSS preprocessor. It allow a simplified syntax and the use of variables. Less CSS is for the Ruby programming language, however it looks like Aaron Russel created an extension for creating cached stylesheets your PHP projects can use.

Get it: http://lesscss.org

Sass

On their website, Sass claims to make CSS fun again. To be honest, I must admit that what this project is capable of is very interesting. Like Less CSS, it allow the use of variables and have a simplified syntax. Sass is definitely a great tool, unfortunely only available for Ruby, as far as I know.

Get it: http://sass-lang.com/

Turbine

If like me, you’re a PHP Lover, here is a css preprocessor made for your favorite language. I haven’t tested it yet, but Turbine looks very cool. It allow a minimal syntax, automatically gzip multiple css, fix cross-browser issues, and a lot more. A must check if you’re into PHP.

Get it: http://turbine.peterkroener.de/index.php

Switch CSS

Switch is a full featured, production ready CSS preprocessor. It runs under Apache with mod_python, or as an environment-agnostic command line tool.

Get it: http://sourceforge.net/projects/switchcss/

CSS Cacheer

CSS Cacheer is a very cool preprocessor which allows developers to create plugins. It requires PHP and Apache with mod_deflate and mod_rewrite in order to work.

Get it: http://retired.haveamint.com/archive/2008/05/30/check_out_css_cacheer

CSS Preprocessor

Another interesting preprocessor, written in PHP 5. Among other things, this tool allow you to use expressions such as margin-left: (200px * 3/2 – 10px); in your stylesheets.

Get it: http://pornel.net/css

DT CSS

DtCSS speeds up CSS coding by extending the features to CSS. Such as nested selectors, color mixing and more. DtCSS reads the CSS file with special syntax written for DtCSS, and outputs the standard CSS. It also comes with a smart caching system.

Get it: http://code.google.com/p/dtcss/

CSS PP

Unfortunely, CSS PP is still in alpha status, but the authors says the code will be released very soon. One of the good points of this projects is that it will be available in PHP, Python and Ruby. Great news for developpers who work with all of these languages.

Get it: http://csspp.org/

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

8 CSS preprocessors to speed up development time

WordPress: How to insert data programmatically

Inserting posts

Do you remember back in 2008, when I created WP Vote? This site was the first (as far as I know) social voting site created 100% within WordPress. Users were able to submit a story, which was automatically published on the blog.

Inserting a post programmatically in WordPress is extremely easy. You have to use the wp_insert_post() function, which takes an array as a parameter.
Here is a working example. If you want to test it, paste the code below on your functions.php file.

global $user_ID;
$new_post = array(
    'post_title' => 'My New Post',
    'post_content' => 'Lorem ipsum dolor sit amet...',
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => $user_ID,
    'post_type' => 'post',
    'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);

Cool, isn’t it? Let have a closer look to the parameters specified in the $new_post array:

  • post_title: the name of the post.
  • post_content: the content of the post
  • post_status: the post status (published, draft, etc)
  • post_date: use date() or specify a custom date
  • post_author: Author id of the post author
  • post_type: Can be post, page, or a custom post type
  • post_category An array of categories ids

Source: http://www.webmaster-source.com/2010/02/09/programmatically-creating-posts-in-wordpress

Inserting comments

Inserting comments is not harder than inserting posts. I personally never used this code, but here is it in case you need it. To give it a try, simply paste it in your functions.php file.

$data = array(
	'comment_post_ID' => 1,
	'comment_author' => 'admin',
	'comment_author_email' => '[email protected]',
	'comment_author_url' => 'http://www.catswhocode.com',
	'comment_content' => 'Lorem ipsum dolor sit amet...',
	'comment_author_IP' => '127.0.0.1',
	'comment_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3',
	'comment_date' => date('Y-m-d H:i:s'),
	'comment_date_gmt' => date('Y-m-d H:i:s'),
	'comment_approved' => 1,
);

$comment_id = wp_insert_comment($data);

Just like the wp_insert_post() function, wp_insert_comment() takes an array as a parameter. Here are the data used:

  • comment_post_ID: ID of the commented post
  • comment_author: Name of the comment author
  • comment_author_email: Email address of the comment author
  • comment_author_url: Website of the comment author
  • comment_content: Text of the comment
  • comment_author_IP: IP address of the comment author
  • comment_agent: User agent of the commenter browser
  • comment_date: Date of the comment
  • comment_date_gmt: GMT date of the comment
  • comment_approved: Is the comment approved? 1 for yes and 0 for “awaiting moderation”

Adding categories to a post

Now that we saw how to insert a post or a comment into WordPress database, let’s see how to make a post part of one (or more) categories. WordPress has a built-in function for that, named wp_set_object_terms().

What you have to do is to create an array with the desired categories ID, and then use the function as shown below:

$category_ids = array(4, 5, 6);
wp_set_object_terms( $post_id, $category_ids, 'category');

The wp_set_object_terms() function take 3 parameters: The post ID, an array of categories ID, and the taxonomy type (In this example, category).

Adding tags to a post

Adding tags to a post is extremely simple as well. Even better, it does not require a new function, you can do so by using wp_set_object_terms().
Take a look at the example below:

$tag_ids = array(7, 8, 9);
wp_set_object_terms( $post_id, $tag_ids, 'post_tag');

Looks very similar with the previous piece of code, which allowed us to add categories to a post, isn’t it? In fact, the only difference is the taxonomy type: Here the parameter is post_tag instead of category.
Source: http://wpprogrammer.com/snippets/add-a-category-or-tag-to-a-post-programatically/

Automatically create a custom field when a post is published

I recently had a client who wanted to have a custom field created automatically, each time he published a new post, so he wouldn’t have to create a custom field with a default value for each article he wrote.
This piece of code was a real life-saver: Just paste it on your functions.php file and publish a new post: A custom field has been created automatically.

function add_custom_field_automatically($post_ID) {
	global $wpdb;
	if(!wp_is_post_revision($post_ID)) {
		add_post_meta($post_ID, 'field-name', 'custom value', true);
	}
}
add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_automatically');

So how does it work? First, a function has been created. This function make sure the post isn’t a revision on then adds a custom field named field-name, with custom value as a value.
Then, a “hook” is used to make sure that every time a post or page will be published, the add_custom_field_automatically() function will be called.
Source: http://wpcanyon.com/tipsandtricks/adding-a-custom-field-automatically-on-postpage-publish/

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

WordPress: How to insert data programmatically

WordPress function: Get category ID using category name

As usual, let’s start by pasting the function in your functions.php file:

function get_category_id($cat_name){
	$term = get_term_by('name', $cat_name, 'category');
	return $term->term_id;
}

Once you saved the file, just call the function with your category name as a parameter. Example:

$category_ID = get_category_id('WordPress Tutorials');

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress function: Get category ID using category name

How to display your average feed readers

As usual, the first thing to do is to paste the function in your functions.php file:

function get_average_readers($feed_id,$interval = 7){
	$today = date('Y-m-d', strtotime("now"));
	$ago = date('Y-m-d', strtotime("-".$interval." days"));
	$feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $feed_url);
	$data = curl_exec($ch);
	curl_close($ch);
	$xml = new SimpleXMLElement($data);
	$fb = $xml->feed->entry['circulation'];

	$nb = 0;
	foreach($xml->feed->children() as $circ){
		$nb += $circ['circulation'];
	}

	return round($nb/$interval);
}

Once done, you can call the function wherever you want in your theme files. Pass your Feedburner feed id as a parameter:

<?php
$nb = get_average_readers('catswhocode');
echo "I have ".$nb." RSS readers";
?>

Code initially published on Cats Who Blog.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

How to display your average feed readers

Add categories or tags to post programatically

The first thing to do is to create an array of categories id. Once done, you simply have to use the wp_set_object() function, which take 3 parameters: The post id, an array of categories to add to the post, and the taxonomy type (category in this example).

$category_ids = array(4, 5, 6);
wp_set_object_terms( $post_id, $category_ids, 'category');

Adding tags to a post is extremely easy as well. The only difference with the code to add categories is the taxonomy “post_tag” instead of “category”.

$tag_ids = array(7, 8, 9);
wp_set_object_terms( $post_id, $tag_ids, 'post_tag');

Thanks to WPProgrammer for this very cool snippet.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

Add categories or tags to post programatically

10 life-saving PHP snippets

Highlight specific words in a phrase

Sometimes, for example, when displaying search results, it is a great idea to highlight specific words. This is exactly what the following function can do:

function highlight($sString, $aWords) {
	if (!is_array ($aWords) || empty ($aWords) || !is_string ($sString)) {
		return false;
	}

	$sWords = implode ('|', $aWords);
 	return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
}

Source: http://www.phpsnippets.info/highlights-words-in-a-phrase

Get your average Feedburner subscribers

Recently, Feedburner counts had lots of problems and it’s hard to say that the provided info is still relevant. This code will grab your subscriber count from the last 7 days and will return the average.

function get_average_readers($feed_id,$interval = 7){
	$today = date('Y-m-d', strtotime("now"));
	$ago = date('Y-m-d', strtotime("-".$interval." days"));
	$feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL, $feed_url);
	$data = curl_exec($ch);
	curl_close($ch);
	$xml = new SimpleXMLElement($data);
	$fb = $xml->feed->entry['circulation'];

	$nb = 0;
	foreach($xml->feed->children() as $circ){
		$nb += $circ['circulation'];
	}

	return round($nb/$interval);
}

Source: http://www.catswhoblog.com/how-to-get-a-more-relevant-feedburner-count

Automatic password creation

Although I personally prefer leaving users to choose their password themselves, a client recently asked me to generate passwords automatically when a new account is created.
The following function is flexible: You can choose the desired length and strength for the password.

function generatePassword($length=9, $strength=0) {
	$vowels = 'aeuy';
	$consonants = 'bdghjmnpqrstvz';
	if ($strength >= 1) {
		$consonants .= 'BDGHJLMNPQRSTVWXZ';
	}
	if ($strength >= 2) {
		$vowels .= "AEUY";
	}
	if ($strength >= 4) {
		$consonants .= '23456789';
	}
	if ($strength >= 8 ) {
		$vowels .= '@#$%';
	}

	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++) {
		if ($alt == 1) {
			$password .= $consonants[(rand() % strlen($consonants))];
			$alt = 0;
		} else {
			$password .= $vowels[(rand() % strlen($vowels))];
			$alt = 1;
		}
	}
	return $password;
}

Source: http://www.phpsnippets.info/generate-a-password-in-php

Compress multiple CSS files

If you’re using different CSS files on your site, they might take quite long to load. Using PHP, you can compress them into a single file with no unnecessary white spaces or comments.
This snippet has been previously discussed on my “3 ways to compress CSS files using PHP” article.

header('Content-type: text/css');
ob_start("compress");
function compress($buffer) {
  /* remove comments */
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
  /* remove tabs, spaces, newlines, etc. */
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
  return $buffer;
}

/* your css files */
include('master.css');
include('typography.css');
include('grid.css');
include('print.css');
include('handheld.css');

ob_end_flush();

Source: http://www.phpsnippets.info/compress-css-files-using-php

Get short urls for Twitter

Are you on Twitter? If yes, you probably use a url shortener such as bit.ly or TinyUrl to share your favorite blog posts and links on the network.
This snippet take a url as a parameter and will return a short url.

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

Source: http://www.phpsnippets.info/convert-url-to-tinyurl

Calculate age using date of birth

Pass a birth date to this function, and it will return the age of the person; very useful when building communities or social media sites.

function age($date){
	$year_diff = '';
	$time = strtotime($date);
	if(FALSE === $time){
		return '';
	}

	$date = date('Y-m-d', $time);
	list($year,$month,$day) = explode("-",$date);
	$year_diff = date("Y") – $year;
	$month_diff = date("m") – $month;
	$day_diff = date("d") – $day;
	if ($day_diff < 0 || $month_diff < 0) $year_diff–;

	return $year_diff;
}

Source: John Karry on http://www.phpsnippets.info/calculate-age-of-a-person-using-date-of-birth

Calculate execution time

For debugging purposes, it is a good thing to be able to calculate the execution time of a script. This is exactly what this piece of code can do.

//Create a variable for start time
$time_start = microtime(true);

// Place your PHP/HTML/JavaScript/CSS/Etc. Here

//Create a variable for end time
$time_end = microtime(true);
//Subtract the two times to get seconds
$time = $time_end - $time_start;

echo 'Script took '.$time.' seconds to execute';

Source: http://phpsnips.com/snippet.php?id=26

Maintenance mode with PHP

When updating your site, it is generally a good thing to temporarily redirect your users to a “Maintenance” page so they will not see any critical info such as error messages.
This is generally done using an .htaccess file, but it can be done easily with PHP:

function maintenance($mode = FALSE){
    if($mode){
        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
            header("Location: http://example.com/maintenance.php");
            exit;
        }
    }else{
        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
            header("Location: http://example.com/");
            exit;
        }
    }
}

Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php

Prevent js and css files from being cached

By default, external files such as javascript and css are cached by the browser. If you want to prevent this from caching, simply use this easy tip:

<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /&glt;

The result will look like this:

<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css" /&glt;

Source: http://davidwalsh.name/prevent-cache

Add (th, st, nd, rd, th) to the end of a number

Another useful snippet which will automatically add st, nd, rd or th after a number.

function make_ranked($rank) {
	$last = substr( $rank, -1 );
	$seclast = substr( $rank, -2, -1 );
	if( $last > 3 || $last == 0 ) $ext = 'th';
	else if( $last == 3 ) $ext = 'rd';
	else if( $last == 2 ) $ext = 'nd';
	else $ext = 'st'; 

	if( $last == 1 && $seclast == 1) $ext = 'th';
	if( $last == 2 && $seclast == 1) $ext = 'th';
	if( $last == 3 && $seclast == 1) $ext = 'th'; 

	return $rank.$ext;
}

Source: http://phpsnips.com/snippet.php?id=37

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

10 life-saving PHP snippets

Display dates as “time ago”, the easy way

To display human readable dates on your blog, you have to use the human_time_diff() function. The following piece of code will show a post date like “Posted 6 days ago”.
Paste it anywhere within the loop, save the file, and you’re done.

Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; ?>

Credits: PHP Snippets.

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

Display dates as “time ago”, the easy way

WordPress hack: Use includes in your posts or pages

The first step is to paste the following code in your function.php file:

function digwp_includeContentShortcode($atts) {

  $thepostid = intval($atts[postidparam]);
  $output = '';

  query_posts("p=$thepostid&post_type=page");
  if (have_posts()) : while (have_posts()) : the_post();
    $output .= get_the_content($post->ID);
  endwhile; else:
    // failed, output nothing
  endif;
  wp_reset_query();

  return $output;

}

Once done, you can use the shortcode in your posts or pages, with the following syntax:

[digwp_include postidparam=XXXX]

postidparam is the ID of the post you want to include.

Credits goes to Chris Coyier for this awesome shortcode!

Looking for WordPress hosting? Try WP Web Host. Prices starts at $5/month and you can try it for free!

WordPress hack: Use includes in your posts or pages