How to create a built-in contact form for your WordPress theme

Getting Ready

You can see the working form on my site PHP Snippets. It is a site of mine, so don’t hesitate to grab the RSS feed and follow it on Twitter if you want.

Step 1: Creating the page template

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 form

Now, 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 handling

Our 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 verification

Our 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

How to programatically remove WordPress dashboard widgets

Simply paste the following into your functions.php file. The code will remove all dashboard widgets, so you should comment lines related to wigets you’d like to keep.

function remove_dashboard_widgets() {
	global $wp_meta_boxes;

	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);

}

if (!current_user_can('manage_options')) {
	add_action('wp_dashboard_setup', 'remove_dashboard_widgets' );
}

Thanks to NoScope for this code!

By the way, did you had a look to my latest post on CatsWhoCode about WP 3.0 custom post types?

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

How to programatically remove WordPress dashboard widgets

How to create a side blog with WordPress 3.0

Getting 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 type

Ok, 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 data

Now 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:

Creating a page template to list custom post types

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.

<?php
/*
Template Name: Promo codes Page
*/
?>
<?php get_header() ?>

	<div id="container">
		<div id="content" class="coupons">
			<h1 class="entry-title"><?php the_title(); ?></h1>
			<?php the_content(); ?>

			<?php global $wp_query;
			$page_num = $paged;
			if($pagenum='') $pagenum=1;

			$wp_query = new WP_Query("showposts=20&post_type=coupons&post_status=publish&paged=".$page_num);

			while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

				<div class="post" id="post-<?php the_ID(); ?>">
					<h2><?php the_title(); ?></h2>
					<div class="exerpt"><?php the_excerpt(); ?></div>
				</div><!-- .post -->

			<?php endwhile; ?>

			<div class="navigation"><p><?php posts_nav_link(); ?></p></div>

		</div><!-- #content -->
	</div><!-- #container -->

<?php get_sidebar() ?>
<?php get_footer() ?>

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

How to automatically create a custom field when a post is published

Paste the code below into your functions.php file. The only thing you have to do is to edit the cutsom field name on line 6.

add_action('publish_page', 'add_custom_field_automatically');
add_action('publish_post', 'add_custom_field_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);
	}
}

Thanks to wpCanyon for this cool tip!

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

How to automatically create a custom field when a post is published

WordPress hack: Display post thumbnail in your RSS feed

Simply paste the following code in your functions.php file. The post thumbnail should be visible once you saved the file.

function diw_post_thumbnail_feeds($content) {
	global $post;
	if(has_post_thumbnail($post->ID)) {
		$content = '<div>' . get_the_post_thumbnail($post->ID) . '</div>' . $content;
	}
	return $content;
}
add_filter('the_excerpt_rss', 'diw_post_thumbnail_feeds');
add_filter('the_content_feed', 'diw_post_thumbnail_feeds');

Thanks to Jeff Starr for this great tip!

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

WordPress hack: Display post thumbnail in your RSS feed

10 PHP code snippets for working with strings

Automatically 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 $end

This 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 hyperlinks

If 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 Twitter

As 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://snipplr.com/view.php?codeview&id=31648

Remove URLs from string

When 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 slugs

Need 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 files

CSV (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 string

If 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 pattern

Some 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:

function String_Begins_With($needle, $haystack {
    return (substr($haystack, 0, strlen($needle))==$needle);
}

Source: http://snipplr.com/view.php?codeview&id=2143

Extract emails from a string

Ever 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...

        [email protected]

        Test different formats:
        [email protected];
        <a href="[email protected]">foobar</a>
        <[email protected]>

        strange formats:
        [email protected]
        test6[at]example.org
        [email protected]
        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

WordPress hack: Remove admin name in comments class

This code simply have to be pasted in your functions.php file to work:

function remove_comment_author_class( $classes ) {
	foreach( $classes as $key => $class ) {
		if(strstr($class, "comment-author-")) {
			unset( $classes[$key] );
		}
	}
	return $classes;
}
add_filter( 'comment_class' , 'remove_comment_author_class' );

Thanks to C. Bavota for this interesting piece of code!

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

WordPress hack: Remove admin name in comments class

Best practices for coding HTML emails

Keep 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.


(Yoast.com Newsletter)

Don’t abuse images

An 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 tables

As 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 server

Among 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 attributes

In 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 format

It 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 clients

When 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.

Use Google Analytics to track conversions

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

WordPress tip: Automatically empty Trash

Simply open your wp-config.php file (located at the root of your WOrdPress install) and paste the following code:

define('EMPTY_TRASH_DAYS', 10 );

The second parameter is when to empty trash, in days.

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

WordPress tip: Automatically empty Trash

Thematic WordPress Theme Toolbox: 10 extremely useful hooks

If you’re looking for a tutorial on how to create a Thematic child theme, you should read this post.

Add a favicon

A 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:

function childtheme_favicon() { ?>
	<link rel="shortcut icon" href="<?php echo bloginfo('stylesheet_directory') ?>/images/favicon.png" />
<?php }
add_action('wp_head', 'childtheme_favicon');

Source:

Add an Internet Explorer specific stylesheet

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:

function childtheme_ie_style() { ?>
	<!--[if IE]>
		<link rel="stylesheet" type="text/css" href="http://www.webdevcat.com/wp-content/themes/webdevcat/ie.css" />
	<![endif]-->
<?php }
add_action('wp_head', 'childtheme_ie_style');

Modify Doctype

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 feeds

Feedburner 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 theme

Google 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!

function ga(){ ?>
	<script type="text/javascript">
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
	</script>
	<script type="text/javascript">
	try {
	var pageTracker = _gat._getTracker("UA-XXXXX-10");
	pageTracker._trackPageview();
	} catch(err) {}</script>
<?php }
add_action('wp_footer', 'ga');

Modify Thematic footer credit

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 &copy; 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> &amp; 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 header

Want 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 text

Thematic “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 comments

By 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 template

If 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.

function remove_access() {
    if (is_page_template('affiliate.php')) {
        remove_action('thematic_header','thematic_access',9);
    }

add_action('wp_head','remove_access');
}

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

WordPress hack: Insert comments programatically

The following code can be pasted anywhere on your theme files.
Once this code is executed, it will add a new comment into WordPress database. The returned value is the comment ID, or 0 if a problem happenned.

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

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

WordPress hack: Insert comments programatically

WordPress hack: Get popular posts by comments count

Simply paste the following code where you want to display your most popular posts to be displayed:

$pop = $wpdb->get_results("SELECT id, post_title, comment_count FROM {$wpdb->prefix}posts WHERE post_type='post' ORDER BY comment_count DESC LIMIT 10");

<ul>
foreach($pop as $post) : ?>
<li> <?php echo $post->post_title; ?> </li>
<?php endforeach; ?>
</ul>

Thanks to Neil Skoglund 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 hack: Get popular posts by comments count

10 sites developers should have in their bookmarks

Mysql 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

Script Src

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

Em Chart

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

Twitter API Explorer

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

Browser Sandbox

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

PHP Forms

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

.htaccess editor

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

Smush it!

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/

CSS Compressor

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

Test everything

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

WordPress tip: Quickly secure plugin files

WordPress tip: Quickly secure plugin files

Paste the following in your .htaccess file. Don’t forget to backup the file before edition!

<Files ~ "\.(js|css)$">
  order allow,deny
  allow from all
</Files>

This recipe has been submitted by Greg Winiarski. Thanks for your contribution!

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

WordPress tip: Quickly secure plugin files

Top WordPress hacks of early 2010

Top WordPress hacks of early 2010

Display an incrementing number on each post

I always loved how A List Apart numbers its posts. The following hack will let you do the same with your own blog, using a custom field.

Implementing this hack is quite simple. First, paste the following function into your functions.php file:

function updateNumbers() {
  global $wpdb;
  $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
  $counts = 0 ;
  if ($pageposts):
    foreach ($pageposts as $post):
      setup_postdata($post);
      $counts++;
      add_post_meta($post->ID, 'incr_number', $counts, true);
      update_post_meta($post->ID, 'incr_number', $counts);
    endforeach;
  endif;
}  

add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Once done, you can display the post number with the following code. Note that it have to be used within the loop.

<?php echo get_post_meta($post->ID,'incr_number',true); ?>

Source: http://www.wprecipes.com/how-to-display-an-incrementing-number-next-to-each-published-post

Allow your contributors to upload files

If you’re like me, you have guest contributing articles on your blog and you might be annoyed that the contributor role doesn’t allow file uploads. Most blog posts need images to stand out of the crowd so
this hack is extremely handy: Just paste it on your function.php file and your contributors will be allowed to upload files in the WordPress dashboard. How cool is that?

if ( current_user_can('contributor') && !current_user_can('upload_files') )
    add_action('admin_init', 'allow_contributor_uploads');

function allow_contributor_uploads() {
    $contributor = get_role('contributor');
    $contributor->add_cap('upload_files');
}

Source: http://www.wprecipes.com/wordpress-tip-allow-contributors-to-upload-files

Display “time ago” dates

Twitter has a very cool function which displays the elapsed time since a tweet has been published. What about doing the same with WordPress? Of course it’s possible!
This code just needs to be pasted in your functions.php file. Once you saved the file, posts that were published less than 24 hours ago will display “Published XX ago” instead of regular dates.

add_filter('the_time', 'timeago');

function timeago() {
    global $post;
    $date = $post->post_date;
    $time = get_post_time('G', true, $post);
    $time_diff = time() - $time;
    if ( $time_diff > 0 && $time_diff < 24*60*60 )
        $display = sprintf( __('%s ago'), human_time_diff( $time ) );
    else
        $display = date(get_option('date_format'), strtotime($date) );

    return $display;
}

By the way, if you’re on Twitter do not hesitate to follow me!
Source: http://aext.net/2010/04/display-timeago-for-wordpress-if-less-than-24-hours/

WordPress navigation outside the loop

WordPress provides some functions which allow you to link to the next and previous posts. However, those functions have to be used within the loop. Jeff Starr, who wrote the Digging into WordPress book, has the solution to this problem.
Simply paste the code below on your single.php file, where you’d like to link to the next and previous posts. Or even better, put the code in a php file and then include it in your theme file.

<?php if(is_single()) { // single-view navigation ?>
	<?php $posts = query_posts($query_string); if (have_posts()) : while (have_posts()) : the_post(); ?>
		<?php previous_post_link(); ?> | <?php next_post_link(); ?>
	<?php endwhile; endif; ?>
<?php } else { // archive view navigation ?>
		<?php posts_nav_link(); ?>
<?php } ?>

Source: http://digwp.com/2010/04/post-navigation-outside-loop/

Disallow theme switching

If you’re like me, you’ve created WordPress themes for your clients and already face a problem: The client “explored” the WordPress dashboard and “accidentally” switched the theme.
Using WordPress actions, we can easily remove the “themes” menu and consequently prevent the risk of having a client switching the theme. The code below just has to be pasted in your functions.php. The “themes” menu will be removed once the file is saved.

add_action('admin_init', 'remove_theme_menus');
function remove_theme_menus() {
	global $submenu;	

	unset($submenu['themes.php'][5]);
	unset($submenu['themes.php'][15]);
}

Source: http://soulsizzle.com/quick-tips/stopping-clients-from-switching-their-wordpress-theme/

Get rid of unused shortcodes in your posts

WordPress shortcodes are extremely useful, but they have a weak point: If you use a shortcode in your posts and then stop to use it for some reason, the shortcode code (Like [shortcode] for example) will stay in your posts.

To get rid of unused shortcodes, you just have to execute this line of SQL code. This can be done using PhpMyAdmin or the SQL command line interpreter. Don’t forget to replace [tweet] by the unused shortcode you’d like to delete from your posts.

UPDATE wp_post SET post_content = replace(post_content, '[tweet]', '' );

Source: http://www.wprecipes.com/wordpress-tip-get-rid-of-unused-shortcodes

Switch WordPress theme programmatically

Recently, I worked on an interesting project where I had to switch the blog theme automatically. As the current WordPress theme name is saved in the wp_options table of your WordPress database, we can easily change it.
The cleanest way to do it is definitely to use the update_option() function, as shown in the function below. Paste it in your functions.php file.

function updateTheme($theme){
    update_option('template', $theme);
    update_option('stylesheet', $theme);
    update_option('current_theme', $theme);
}

Once you’ve added the function to your functions.php file, you can call it wherever you need it:

<php updateTheme('default'); ?>

Modify WordPress dashboard footer text

Another good tip for those who create WordPress themes for clients is to modify the WordPress dashboard footer text, and add (for example) a link to your support forum. The only thing you have to do is to copy this code and paste it in functions.php:

function remove_footer_admin () {
    echo "Your own text";
} 

add_filter('admin_footer_text', 'remove_footer_admin');

Source: http://www.wprecipes.com/wordpress-tip-how-to-change-the-dashboard-footer-text

Programmatically Creating Posts in WordPress

If for some reason you need to programmatically insert posts in WordPress database, you’ll be amazed to see how easy is it. The wp_insert_post() takes an array of data as a parameter, and then return the post ID.

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

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

WordPress 3.0: Query custom post types

WordPress 3.0 should be released soon. And I don’t know about you, but personally, I can’t wait. Lots of exiting features are scheduled. One of them is particularly interesting in my opinion: the custom post types, which allow you to define a custom type for a post.
In order to be able to retrieve posts of a specific type from a WordPress database, you can use the following loop, which will get the albums post type:

<ul>
<?php global $wp_query;
$wp_query = new WP_Query("post_type=albums&post_status=publish");

while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>

</ul>

Source: http://www.catswhocode.com/blog/8-useful-code-snippets-to-get-started-with-wordpress-3-0

Please note that I’m currently accepting freelance work; so if you need any kind of WordPress help, I’ll be happy to help you. Simply send me an email and I’ll get back to you.

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

Top WordPress hacks of early 2010