You are hereFeed aggregator / Sources / Cats Who Code
Cats Who Code
How to easily create charts using jQuery and HTML5
Mon, 08/23/2010 - 04:30Step 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!</title> </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 dataNow 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 happenAlright, 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 explanationsGenerating 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
Categories: Web Development
8 examples of stunning CSS3 text effects
Sun, 08/15/2010 - 12:36How 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/
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/
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
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
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
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/
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
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
Categories: Web Development
8 CSS preprocessors to speed up development time
Mon, 08/09/2010 - 10:05Less 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
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/
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 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 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
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
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/
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
Categories: Web Development
WordPress: How to insert data programmatically
Sun, 08/01/2010 - 13:56Inserting 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.
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 commentsInserting 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' => 'admin@admin.com', '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”
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 postAdding 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:
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/
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.
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
Categories: Web Development
10 life-saving PHP snippets
Mon, 07/19/2010 - 10:06Highlight 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 subscribersRecently, 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 creationAlthough 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.
Source: http://www.phpsnippets.info/generate-a-password-in-php
Compress multiple CSS filesIf 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.
Source: http://www.phpsnippets.info/compress-css-files-using-php
Get short urls for TwitterAre 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.
Source: http://www.phpsnippets.info/convert-url-to-tinyurl
Calculate age using date of birthPass 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 timeFor 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 PHPWhen 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:
Source: http://www.phpsnippets.info/easy-maintenance-mode-with-php
Prevent js and css files from being cachedBy 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 numberAnother 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
Categories: Web Development
How to create a built-in contact form for your WordPress theme
Mon, 06/28/2010 - 10:23Getting Ready
A buil-in WordPress form was initially created on my site PHP Snippets, however, thanks to stupid people who sent hundreds of “test” emails from this form, I have taken it offline.
It looked like this:
The first step is to create a page template. To do so, copy the page.php code into a new file named page-contact.php.
We have to add a comment at the beginning of the contact.php file to make sure WordPress will treat the file as a page template. Here’s the code:
<?php /* Template Name: Contact */ ?>Your contact.php file should look like this:
<?php /* Template Name: Contact */ ?> <?php get_header() ?> <div id="container"> <div id="content"> <?php the_post() ?> <div id="post-<?php the_ID() ?>" class="post"> <div class="entry-content"> </div><!-- .entry-content -> </div><!-- .post--> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar() ?> <?php get_footer() ?>Step 2: Building the formNow, we have to create a simple contact form. Simply paste the following code within the entry-content div.
<form action="<?php the_permalink(); ?>" id="contactForm" method="post"> <ul> <li> <label for="contactName">Name:</label> <input type="text" name="contactName" id="contactName" value="" /> </li> <li> <label for="email">Email</label> <input type="text" name="email" id="email" value="" /> </li> <li> <label for="commentsText">Message:</label> <textarea name="comments" id="commentsText" rows="20" cols="30"></textarea> </li> <li> <button type="submit">Send email</button> </li> </ul> <input type="hidden" name="submitted" id="submitted" value="true" /> </form>Nothing hard with this pretty self-explanatory html code for our form. Note the input type=”hidden” I added on line 19: It will be used later to check if the form has been submitted.
Step 3: data processing and error handlingOur form looks pretty good, but right it is very useless because it does not send any email. What we have to do is to verify if the form has been submitted then verify if fields have been filled correctly.
If fields are correctly filled, we’ll get the blog admin email and send them the email. Otherwise, no email will be sent and errors will be displayed to the user.
Paste the following code between the Page Template declaration and the get_header() function:
<?php if(isset($_POST['submitted'])) { if(trim($_POST['contactName']) === '') { $nameError = 'Please enter your name.'; $hasError = true; } else { $name = trim($_POST['contactName']); } if(trim($_POST['email']) === '') { $emailError = 'Please enter your email address.'; $hasError = true; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) { $emailError = 'You entered an invalid email address.'; $hasError = true; } else { $email = trim($_POST['email']); } if(trim($_POST['comments']) === '') { $commentError = 'Please enter a message.'; $hasError = true; } else { if(function_exists('stripslashes')) { $comments = stripslashes(trim($_POST['comments'])); } else { $comments = trim($_POST['comments']); } } if(!isset($hasError)) { $emailTo = get_option('tz_email'); if (!isset($emailTo) || ($emailTo == '') ){ $emailTo = get_option('admin_email'); } $subject = '[PHP Snippets] From '.$name; $body = "Name: $name \n\nEmail: $email \n\nComments: $comments"; $headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?>What I’ve done here was simply to make sure that the form has been submitted and filled correctly. If an error, such as an empty field or incorrect email address occurred, a message is returned and the form isn’t submitted.
Now we have to display error messages below the related field, for example “Please enter your name”. Below you’ll find the complete form page template that you can use “as it”.
<?php /* Template Name: Contact */ ?> <?php if(isset($_POST['submitted'])) { if(trim($_POST['contactName']) === '') { $nameError = 'Please enter your name.'; $hasError = true; } else { $name = trim($_POST['contactName']); } if(trim($_POST['email']) === '') { $emailError = 'Please enter your email address.'; $hasError = true; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) { $emailError = 'You entered an invalid email address.'; $hasError = true; } else { $email = trim($_POST['email']); } if(trim($_POST['comments']) === '') { $commentError = 'Please enter a message.'; $hasError = true; } else { if(function_exists('stripslashes')) { $comments = stripslashes(trim($_POST['comments'])); } else { $comments = trim($_POST['comments']); } } if(!isset($hasError)) { $emailTo = get_option('tz_email'); if (!isset($emailTo) || ($emailTo == '') ){ $emailTo = get_option('admin_email'); } $subject = '[PHP Snippets] From '.$name; $body = "Name: $name \n\nEmail: $email \n\nComments: $comments"; $headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; } } ?> <?php get_header(); ?> <div id="container"> <div id="content"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-content"> <?php if(isset($emailSent) && $emailSent == true) { ?> <div class="thanks"> <p>Thanks, your email was sent successfully.</p> </div> <?php } else { ?> <?php the_content(); ?> <?php if(isset($hasError) || isset($captchaError)) { ?> <p class="error">Sorry, an error occured.<p> <?php } ?> <form action="<?php the_permalink(); ?>" id="contactForm" method="post"> <ul class="contactform"> <li> <label for="contactName">Name:</label> <input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" /> <?php if($nameError != '') { ?> <span class="error"><?=$nameError;?></span> <?php } ?> </li> <li> <label for="email">Email</label> <input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" /> <?php if($emailError != '') { ?> <span class="error"><?=$emailError;?></span> <?php } ?> </li> <li><label for="commentsText">Message:</label> <textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea> <?php if($commentError != '') { ?> <span class="error"><?=$commentError;?></span> <?php } ?> </li> <li> <input type="submit">Send email</input> </li> </ul> <input type="hidden" name="submitted" id="submitted" value="true" /> </form> <?php } ?> </div><!-- .entry-content --> </div><!-- .post --> <?php endwhile; endif; ?> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar(); ?> <?php get_footer(); ?>Step 4: Adding jQuery verificationOur form is now working perfectly. But we can enhance it by adding a client side verification. To do so, I’m going to use jQuery and the validate jQuery plugin. This plugin is great because it allows you to verify that a form has been filled correctly, quickly and easily.
The first thing to do is to download the validate plugin and upload it into your theme file (under a /js directory). Once done, paste the following into a new file:
$(document).ready(function(){ $("#contactForm").validate(); });Save it as verif.js in your /js directory.
Now we have to link the javascript files to our theme. Open your header.php file and paste the following within the <head> and </head> tags:
<?php if( is_page('contact') ){ ?> <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.validate.min.js"></script> <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/verif.js"></script> <?php }?>Once done, your form will be validated on the client side by the jQuery validate plugin. How does it work? It simply picks form element which have the css class required and verifies if they’re filled correctly. If not, a message is displayed.
The plugin is powerful and you can do lots of things with it, however this isn’t the purpose of this article. Hope you enjoy your new WordPress form!
Like CatsWhoCode? If yes, don't hesitate to check my other blog CatsWhoBlog: It's all about blogging!
How to create a built-in contact form for your WordPress theme
Categories: Web Development
How to create a side blog with WordPress 3.0
Mon, 06/21/2010 - 10:11Getting ready
So, what are custom post types? That’s simple, custom post types are like a blog post or page, but of a custom defined type.
As an example, I decided to list some promo codes on my other blog CatsWhoBlog. I could have used a good old static page, but updating it and adding new promo codes would have been a pain.
So I created a custom post type, named coupon and a page template to list all coupons. It’s as simple as that, and now managing coupons & promo codes is extremely easy:
Creating the post typeOk, let’s code. The first thing to do is to create a custom post type. To do so, pick up your theme functions.php file, and add the following:
function create_my_post_types() { register_post_type('coupons', array( 'label' => __('Coupons'), 'singular_label' => __('Coupon'), 'public' => true, 'supports' => array( 'title', 'excerpt', 'comments', 'custom-fields' ), 'rewrite' => array( 'slug' => 'coupons', 'with_front' => false ), ) ); } add_action( 'init', 'create_my_post_types' );Once you saved functions.php, you should notice that a new tab appeared in your WordPress dashboard, as shown in the picture below:
So what does this code do?
First, I have created a function which registers a new post type, named coupons. I gave the following parameters to the register_post_type() function:
- label: Nicename of your post type.
- singular_label: Pretty self explanatory, the singular label of your post type.
- public: Allows post type to be seen publicly.
- supports: Array of data of what the post type supports (editor, excerpt, comments, custom fields, etc…)
- rewrite: Parameters for url rewriting and general post type display.
The complete parameter list can be found on WordPress Codex.
Then, I “hooked” this function to WordPress init() function using add_action().
Adding dataNow that the post type has been created, you can add data by clicking on the “Add Coupon” (Or whatever you named it) link in WordPress dashboard menu.
You should see the following:
Now that we have created a custom post type and added some custom posts, we still have to display it. To do so, I have used a page template. You can easily reuse the following code, or adapt it to display in your blog sidebar, for example.
If you want to see a demo of the page template, just click here.
As you can see, the code I’ve used is definitely easy and self-explanatory. In order to fetch a specific post type, you have to specify the parameter post_type=coupons.
That’s all for today, hope you enjoyed this tutorial!
Like CatsWhoCode? If yes, don't hesitate to check my other blog CatsWhoBlog: It's all about blogging!
How to create a side blog with WordPress 3.0
Categories: Web Development
10 PHP code snippets for working with strings
Mon, 06/07/2010 - 12:09Automatically remove html tags from a string
On user-submitted forms, you may want to remove all unnecessary html tags. Doing so is easy using the strip_tags() function:
$text = strip_tags($input, "");Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2
Get the text between $start and $endThis is the kind of function every web developer should have in their toolbox for future use: give it a string, a start, and an end, and it will return the text contained with $start and $end.
function GetBetween($content,$start,$end){ $r = explode($start, $content); if (isset($r[1])){ $r = explode($end, $r[1]); return $r[0]; } return ''; }Source: http://www.jonasjohn.de/snippets/php/get-between.htm
Transform URL to hyperlinksIf you leave a URL in the comment form of a WordPress blog, it will be automatically transformed into a hyperlink. If you want to implement the same functionality in your own website or web app, you can use the following code:
$url = "Jean-Baptiste Jung (http://www.webdevcat.com)"; $url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2
Split text up into 140 char array for TwitterAs you probably know, Twitter only accepts messages of 140 characters or less. If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.
function split_to_chunks($to,$text){ $total_length = (140 - strlen($to)); $text_arr = explode(" ",$text); $i=0; $message[0]=""; foreach ($text_arr as $word){ if ( strlen($message[$i] . $word . ' ') <= $total_length ){ if ($text_arr[count($text_arr)-1] == $word){ $message[$i] .= $word; } else { $message[$i] .= $word . ' '; } } else { $i++; if ($text_arr[count($text_arr)-1] == $word){ $message[$i] = $word; } else { $message[$i] = $word . ' '; } } } return $message; }Source: http://www.phpsnippets.info/split-text-up-into-140-char-array-for-twitter
Remove URLs from stringWhen I see the amount of URLs people try to leave in my blog comments to get traffic and/or backlinks, I think I should definitely give a go to this snippet!
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);Source: http://snipplr.com/view.php?codeview&id=15236
Convert strings to slugsNeed to generate slugs (permalinks) that are SEO friendly? The following function takes a string as a parameter and will return a SEO friendly slug. Simple and efficient!
function slug($str){ $str = strtolower(trim($str)); $str = preg_replace('/[^a-z0-9-]/', '-', $str); $str = preg_replace('/-+/', "-", $str); return $str; }Source: http://snipplr.com/view.php?codeview&id=2809
Parse CSV filesCSV (Coma separated values) files are an easy way to store data, and parsing them using PHP is dead simple. Don’t believe me? Just use the following snippet and see for yourself.
$fh = fopen("contacts.csv", "r"); while($line = fgetcsv($fh, 1000, ",")) { echo "Contact: {$line[1]}"; }Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1
Search for a string in another stringIf a string is contained in another string and you need to search for it, this is a very clever way to do it:
function contains($str, $content, $ignorecase=true){ if ($ignorecase){ $str = strtolower($str); $content = strtolower($content); } return strpos($content,$str) ? true : false; }Source: http://www.jonasjohn.de/snippets/php/contains.htm
Check if a string starts with a specific patternSome languages such as Java have a startWith method/function which allows you to check if a string starts with a specific pattern. Unfortunately, PHP does not have a similar built-in function.
Whatever- we just have to build our own, which is very simple:
Source: http://snipplr.com/view.php?codeview&id=2143
Extract emails from a stringEver wondered how spammers can get your email address? That’s simple, they get web pages (such as forums) and simply parse the html to extract emails. This code takes a string as a parameter, and will print all emails contained within. Please don’t use this code for spam
function extract_emails($str){ // This regular expression extracts all emails from a string: $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; preg_match_all($regexp, $str, $m); return isset($m[0]) ? $m[0] : array(); } $test_string = 'This is a test string... test1@example.org Test different formats: test2@example.org; <a href="test3@example.org">foobar</a> <test4@example.org> strange formats: test5@example.org test6[at]example.org test7@example.net.org.com test8@ example.org test9@!foo!.org foobar '; print_r(extract_emails($test_string));Source: http://www.jonasjohn.de/snippets/php/extract-emails.htm
Like CatsWhoCode? If yes, don't hesitate to check my other blog CatsWhoBlog: It's all about blogging!
10 PHP code snippets for working with strings
Categories: Web Development
Best practices for coding HTML emails
Mon, 05/24/2010 - 10:12Keep it simple and lightweight
If you have to remember only one of all the tips I’m going to give you in this post, it should be this one. In fact, an html email is not a website, so you shouldn’t try to embed a website into an email.
Some years ago, I used to work for a French TV channel and I often had to slice some PSD’s into html emails. The PSD’s contained gradients, funky fonts, and even animated gifs. As a result, the work (despite all efforts I’ve put in it) looked different from one email client to another, the fonts had to be replaced by Arial, and the whole email was extremely heavy and highly relied on images.
On the other hand, a simple html email will loaded smoothly, and will be more pleasant to read.
Don’t abuse imagesAn image is worth a thousand words, but it may also take forever to load. I have received many emails that consisted of a few lines of text and nothing else but big images. As a result, the recipient had to wait until the image was loaded (Which can sometimes takes up to 5 seconds!) in order to read the information embedded in the email.
This is, in my opinion, a waste of time for the recipient, as well as a waste of money for the sender: Most people won’t wait 5 seconds in order to have the big image you send them loaded. They’ll trash the email. It’s as simple as that.
An html email should be beautiful and pleasurable to view, but don’t over do it. Like I’ve just said, keep it simple, you won’t regret it.
Work with tablesAs many email clients handle CSS worst than IE6 (Yes, I’m not joking), you shouldn’t even try to make advanced layouts using CSS. Instead, you should do a jump 10 years ago and say hello to tables, tr’s and td’s again.
If you’re like me, you’re a CSS fan, and this might sound very frustrating. In fact, having to code the dirty way is never pleasant, but you don’t have much of a choice. Do not hesitate to test by yourself: Chances are that you’ll soon be using tables again.
Always use images from your serverAmong html email worst practices I ever saw, embedding images directly in the email definitely arrived at good place. This is wrong in many points: First, it will make the email heavier (I’ve seen 300ko messages!), and secondly, there’s a strong risk that the recipient email client block those images.
What you should do is to create a hierarchy of directories on your server, for example Newsletters and then May_2010, and upload images for your html email in it. Once done, simply call them using absolute url paths:
<img src="http://www.catswhocode.com/images/cat.jpg" alt="A cat" />Write your CSS inline and use html attributesIn email clients, the lack of CSS support is definitely something to keep in mind. Don’t try linking to an external CSS file, and try to avoid as many CSS declarations as possible in the <head> section of your document.
It may be dirty, but the best way to make sure your CSS will be (quite) correctly interpreted by the recipient’s client is to code your CSS the inline way, as shown in the example below:
<p style="background:#069; color: white;">A new background and font color with inline CSS</p>Another “dirty but effective” option to consider is the use of html attributes, such as background or bgcolor:
<body bgcolor="#069">Don’t forget the text formatIt may seems a bit obsolete in 2010, but many people, including myself, prefers the good old “plain text” format than html emails. When creating an email list subscription form, try to allow the visitor to choose between the html and plain text format.
Make sure your emails display in various clientsWhen creating a website, any serious developer will test its render on various browsers. This should be the same with html emails: people use a wide variety of clients and in order to be professional you should try to support most of them.
In my opinion, the following clients should be supported: Gmail, Yahoo mail, Mozilla Thunderbird, Apple Mail and Microsoft Outlook. below, you’ll find two great guides about CSS in html emails:
- Guide to CSS support in email clients: A very interesting guide describing which CSS properties can be used depending on the user’s email client. PDF and Excel versions are downloadable.
- CSS3 support in email clients : Enjoying CSS3? Here’s another great resource brought to you by Campaign Monitor, showing the few CSS3 properties you can already use in your html emails.
Sending a good html email is definitely a great thing, but your goal is to have people click on it and visit your site. There’s lots of way to track clicks on emails, but one of the easiest is to use Google Analytics, that you’re probably already using on your website.
I’ve never been a big email list sender so I never experimented with Google Analytics conversion tracking. Though, it looks like doing so is very easy: All you have to do is to add some GET parameters to your links, as shown in the example below:
<a href="http://www.mysite.com/page.php?utm_campaign=fall-sale&utm_medium=email&utm_source=female-list">Click here</a>However, if you want to know more about click tracking using Google Analytics, you should have a look at this article.
Like CatsWhoCode? If yes, don't hesitate to check my other blog CatsWhoBlog: It's all about blogging!
Best practices for coding HTML emails
Categories: Web Development
Thematic WordPress Theme Toolbox: 10 extremely useful hooks
Tue, 05/18/2010 - 11:42If you’re looking for a tutorial on how to create a Thematic child theme, you should read this post.
Add a faviconA favicon is a small image displayed by modern web browsers. It is a must have for all websites, because it allows your visitors to quickly visualize your site among others when they have lots of browser tabs open at the same time.
This handy code will add your favicon to your theme. Make sure a favicon.png file is in your child theme images directory, and then paste the code in your functions.php file:
Who doesn’t hate Internet Explorer? Unfortunately, most clients will require developers to make their site IE-compliant. And the best way to do so is to use some conditional comments and a dedicated stylesheet.
Create a file named ie.css in your child theme directory, and then insert the following code in your functions.php file:
By default, Thematic outputs a XHTML 1.0 transitional doctype. If for some reason, you prefer using another kind of doctype, pasting the code below in your functions.php will do the trick.
function childtheme_create_doctype($content) { $content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $content .= "\n"; $content .= '<html xmlns="http://www.w3.org/1999/xhtml"'; return $content; } add_filter('thematic_create_doctype', 'childtheme_create_doctype');Use Feedburner RSS feedsFeedburner is very popular among bloggers. If you want to replace default rss feeds by feedburner feeds in Thematic, this code is for you.
function childtheme_rssfeeds($content) { $content = "\t"; $content .= "<link rel=\"alternate\" type=\"application/rss+xml\" href=\""; $content .= "http://feeds2.feedburner.com/Catswhocode"; $content .= "\" title=\""; $content .= wp_specialchars(get_bloginfo('name'), 1); $content .= " " . __('RSS feed', 'thematic'); $content .= "\" />"; $content .= "\n"; return $content; } add_filter('thematic_rss', 'childtheme_rssfeeds');Add Google Analytics code to your Thematic child themeGoogle Analytics is another free and very useful service. In order to allow GA to collect your visitor information and create your stats, you have to insert a small piece of Javascript on your footer.php file.
Insert this code in your functions.php file, save it, and you’re done. Of course, don’t forget to replace the Google Analytics code with your own!
If you’re building a Thematic child theme for a client, you may want to insert your credit link in the footer text. The following code will do it. Don’t forget to give credit to Ian Stewart for his awesome work on the Thematic theme framework!
function my_footer($thm_footertext) { $thm_footertext = 'Copyright © 2010 Jean-Baptiste Jung. <a href="http://www.webdevcat.com">WebDevCat.com</a> is obviously powered by <a href="http://www.wordpress.org">WordPress</a> & the <a href="http://www.themeshaper.com/thematic">Thematic Theme framework</a>.'; return $thm_footertext; } add_filter('thematic_footertext', 'my_footer');Display Thematic menu above headerWant to have your navigation menu above your site header? That’s not a problem. This code will remove the menu from below the header and then put it above it.
function remove_thematic_actions() { remove_action('thematic_header','thematic_access',9); add_action('thematic_aboveheader','search_access',9); } add_action('wp','remove_thematic_actions');Change “more” link textThematic “Read More” link displays Read More » by default. The following code allow you to change the “Read More” text.
function childtheme_more_text($content) { $content = 'Click to read the rest!'; return $content; } add_filter('more_text', 'childtheme_more_text');Change gravatar size in Thematic commentsBy default, Thematic displays 35px*35px gravatars. If you want to change this size, no problem: Just paste this code in, as usual, your beloved functions.php file.
function childtheme_avatarsize() { return '56'; } add_action( 'avatar_size', 'childtheme_avatarsize' );Source: http://themeshaper.com/forums/topic/on-using-avatars-in-thematic
Remove Thematic menu on specific page templateIf you want to make a squeeze page on your site or blog using Thematic, that’s quite easy: You only have to create a page template and remove the menu. To do so, just paste the code below in your functions.php file.
Don’t forget to set your page template name on line 2.
Source: http://themeshaper.com/forums/topic/conditionally-removing-thematic_access
By the way, if you’re interested in Thematic Theme help, don’t hesitate to ask me. I just started freelancing and I’m ready to help you for a reasonable price.
Like CatsWhoCode? If yes, don't hesitate to check my other blog CatsWhoBlog: It's all about blogging!
Thematic WordPress Theme Toolbox: 10 extremely useful hooks
Categories: Web Development
10 sites developers should have in their bookmarks
Sat, 05/08/2010 - 08:30Mysql Format Date
MySQL Format Date helps you to format your dates using the MySQL DATE_FORMAT function. Just select a common date format and then change it to your suit your needs. The MySQL DATE_FORMAT code will be generated at the bottom of the page which you can then copy into your query.
Visit site: http://www.mysqlformatdate.com
Are you tired of hunting the Internet in order to find the script tag for the latest version of the Javascript library of your choice? ScriptSrc.net has compiled all the latest versions of jQuery, Mootools, Prototype and more in a single page which lets you copy it in your browser clipboard with a single click.
Visit site: http://scriptsrc.net
I never been a fan of ems in CSS files, but sometimes you have to deal with it. In that case, Em chart will translate ems to pixels so you’ll save time and hassle.
Visit site: http://aloestudios.com/tools/emchart
If you’re using the Twitter API in the site you build, you’ll for sure enjoy this very handy website which allow you to search through the Twitter API. Even better, the website can generate ready-to-use code snippets. A real time gain for you and your clients!
Visit site: http://twitapi.com/explore
Cross browser compatibility is definitely one of the biggest problems a web developer has to face in his daily job. The browser sandbox lets you run any Windows browser from the web. The only bad thing is that you must run a Windows machine: The app does not work on Macs and GNU/Linux.
Visit site: http://spoon.net/browsers
Web forms are one of the most important part of a website, but creating them is also very time-consuming. So, what about using a website that can speed up your form development for free?
PHP forms allows you to create advanced forms that can fit the needs of most websites.
Visit site: http://www.phpform.org
A .htaccess file is a must have for any website. Don’t know how to write one? No problem, just visit this site to create your .htaccess file using a wizard. It doesn’t allow very advanced stuff, but the results are great for 95% of the websites you’ll make.
Visit site: http://www.htaccesseditor.com/en.shtml
Images may be worth a thousand words, they’re also well known to use a lot of bandwidth. Images can be optimized for the web using programs like Photoshop; but if you don’t own a copy of this software or simply don’t have a clue how to do it, smush.it is what you need.
Brought to you by Yahoo developers network, Smush.it is an online tool that will reduce your image size without reducing their quality. For WordPress users, a very handy plugin for your favorite blogging engine is available here.
Visit site: http://developer.yahoo.com/yslow/smushit/
Especially on site with many different page layouts, CSS files can become huge and use a lot of server bandwidth. This tool, named CSS Compressor, can consequently reduce the size of any CSS file by removing comments, indentation and more.
Even better, compression level can be configured to fit your needs.
Visit site: http://www.csscompressor.com
This site is a definitive must-have for your bookmarks: As the name says, Test everything allows you to test lot of things such as XHTML and CSS markup, PageRank, back-links, and a lot more.
Visit site: http://tester.jonasjohn.de
Like CatsWhoCode? If yes, don't hesitate to check my other blog CatsWhoBlog: It's all about blogging!
10 sites developers should have in their bookmarks
Categories: Web Development