PHP: Fast and easy SQL queries using ezSQL

What’s ezSQL, and why it is useful

On big projects, the usual good practice is to use a CMS or a framework such as Symfony or CodeIgniter to build your site on. But on smaller projects, many developers are still using PHP functions such as mysql_query() to do SQL queries to the database.

While it’s functional, I do not recommend to use all those mysql_XXX functions: Most websites are using MySQL, that’s right, but if one day you have to deal with another DB like PostGres or Oracle… Your code will not work at all, and you’ll have to rewrite it. Scary, isn’t it? This is why is it recommended to use a database abstraction layer, an API which unifies the communication between your application/website and databases such as MySQL, Oracle or PostgreSQL.

As you can guess, ezSQL allows you to work with various databases very easily. Though, please note that it does not support differences in SQL syntax implementations among different databases.

Also, ezSQL provide a few methods which simplify queries to the database, and help producing a cleaner code.

ezSQL and WordPress

As most of you are familiar with WordPress, you probably know the wpdb class, which allows you to send queries to the database. As wpdb is based on ezSQL, and you’re already familiar with the WordPress class, you won’t have any trouble to learn using ezSQL. And don’t worry if you never heard of WordPress or the wpdb class. ezSQL is extremely easy to learn and to use.

Downloading and installing ezSQL

Right, I have talked too much. How about some coding now? Let start by grabbing your copy of ezSQL. Once you have it, unzip on your server (or hard drive).

In order to be able to use ezSQL in your projects, you have to include two files: The first is ez_sql_core.php, which is ezSQL core file. The second depends on the database you’re going to use. In order to use ezSQL with a MySQL database, you have to include ez_sql_mysql.php.

Once done, you have to create a ezSQL object. This is done easily using your database username, password, name and host. The following example demonstrates the inclusion of the required files and the creation of a ezSQL object:

include_once "../shared/ez_sql_core.php";
include_once "ez_sql_mysql.php";
$db = new ezSQL_mysql('db_user','db_password','db_name','db_host');

Now, you have an object called $db. We’ll use it run any types of queries to our database.

Queries examples

ezSQL has a few methods to make SQL queries extremely simple. Let’s see what you can do with it:

Execute any query

In order to insert, delete or most generally, run any kind of query to the database, we have to use the query method. In case of a data insertion, the method will return the insert id.

$db->query("INSERT INTO users (id, name, email) VALUES (NULL,'The Cat','[email protected]')");

Example of an update query:

$db->query("UPDATE users SET name = 'Patrick' WHERE id = 4");

Select a row

The get_row method is great if you just need to select a row from your database. The example below executes a simple select query and displays the results.

$user = $db->get_row("SELECT name, email FROM users WHERE id = 4");

echo $user->name;
echo $user->email;

Select a single variable

If you only need a variable, the get_var method is here to help. Using it is extremely simple as shown below.

$var = $db->get_var("SELECT count(*) FROM users");

echo $var;

Select multiple results

Although the methods documented above are quite useful, most of the time you’ll need to get various rows of data from your database. The method called get_results will get various data from your database. To output the data, a simple foreach() loop is all you need.

$results = $db->get_results("SELECT name, email FROM users");

foreach ( $results as $user ) {
    echo $user->name;
    echo $user->email;
}

Select a column

If you need to get a column, you can use the get_col method. The second parameter is the column offset.

foreach ( $db->get_col("SELECT name,email FROM users",0) as $name ) {
            echo $name;
}

Debug

When something doesn’t work as expected, ezSQL has a great method to perform some debugging. Not surprising, the method is called debug. When called, the method will display the last query performed and its associated results.

$db->debug();

I hope you enjoyed this article and that you’ll use ezSQL in your future projects. It’s a great tool which was very helpful for me many times!

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

PHP: Fast and easy SQL queries using ezSQL

How to easily get post ancestors

In order to get the post ancestors (also called parents) simply use the get_post_ancestors() function. This function takes a single argument which can be either the post ID or post object, and return the ancestors IDs as an array.

$ancestors = get_post_ancestors($post);

Thanks to Coen Jacobs for this great piece of code!

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

How to easily get post ancestors

How to create a kick-ass CSS3 progress bar

Please note: The original CSS3 progress bar shown in this tutorial has been created by Ivan Vanderbyl, which hereby gave me the right to reproduce and document his work.
The following tutorial and the demo works best on Chrome and Safari, correctly on Firefox and very badly in Internet Explorer (eh…I’m sure you hadn’t guessed that).

The Demo


Click on the image to view a live demo. You can also get the source on Github.

Getting ready

Let’s start by organizing our work. To achieve the effect of this tutorial, we’ll need to create 3 files:

  • progress.html, which will contain our markup.
  • ui.css which will contain our CSS styles.
  • progress.js which will contain some additional jQuery animations.

Create a directory on your webserver (or hard drive) and create the files.

The HTML markup

Here we go. Open your progress.html file and paste the following markup in it:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Pure CSS Progress Bar</title>

	<link rel="stylesheet" href="stylesheets/ui.css">
	<link rel="stylesheet" href="stylesheets/ui.progress-bar.css">
</head>
<body>
	<div id="container">
		<div id="progress_bar" class="ui-progress-bar ui-container">
        	<div class="ui-progress" style="width: 79%;">
				<span class="ui-label" style="display:none;">Processing <b class="value">79%</b></span>
      		</div><!-- .ui-progress -->
    	</div><!-- #progress_bar -->  

		<div class="content" id="main_content" style="display: none;">
	    	<p>Hello, World!</p>
	  	</div><!-- #main_content -->
	</div><!-- #container -->
</body>
</html>

Let me explain the code a bit: On line 1, I’ve declared a HTML5 doctype. Then, lines 12 to 16 contains the markup for the progress bar itself. If you save the file and view it in your browser right now, you’ll see that nothing appears. Don’t worry, we’re going to apply so CSS3 magic in a minute.

Diving into CSS3

Open your ui.css file and paste the following code in it. There’s nothing fancy there, just some basic styles (that I’ve simplified from the original source) for the layout.

body {
  background:#eee;
  padding: 30px;
  font-size: 62.5%;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  position: relative;
  margin: 0;
}

#container {
  margin: 0 auto;
  width: 460px;
  padding: 2em;
  background: #DCDDDF;

}

.ui-progress-bar {
  margin-top: 3em;
  margin-bottom: 3em;
} 

.ui-progress span.ui-label {
  font-size: 1.2em;
  position: absolute;
  right: 0;
  line-height: 33px;
  padding-right: 12px;
  color: rgba(0,0,0,0.6);
  text-shadow: rgba(255,255,255, 0.45) 0 1px 0px;
  white-space: nowrap;
}

Once you are done, we can finally get into more serious things. The code below will make your progress bar come to life. I’ll explain it in details in a minute. For now, copy it and paste it in your ui.css file.

@-webkit-keyframes animate-stripes {
  from {
    background-position: 0 0;
  }

  to {
   background-position: 44px 0;
  }
}      

.ui-progress-bar {
  position: relative;
  height: 35px;
  padding-right: 2px;
  background-color: #abb2bc;
  border-radius: 35px;
  -moz-border-radius: 35px;
  -webkit-border-radius: 35px;
  background: -webkit-gradient(linear, left bottom, left top, color-stop(0, #b6bcc6), color-stop(1, #9da5b0));
  background: -moz-linear-gradient(#9da5b0 0%, #b6bcc6 100%);
  -webkit-box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #FFF;
  -moz-box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #FFF;
  box-shadow: inset 0px 1px 2px 0px rgba(0, 0, 0, 0.5), 0px 1px 0px 0px #FFF;
}        

.ui-progress {
  position: relative;
  display: block;
  overflow: hidden;
  height: 33px;
  -moz-border-radius: 35px;
  -webkit-border-radius: 35px;
  border-radius: 35px;
  -webkit-background-size: 44px 44px;
  background-color: #74d04c;
  background: -webkit-gradient(linear, 0 0, 44 44,
    color-stop(0.00, rgba(255,255,255,0.17)),
    color-stop(0.25, rgba(255,255,255,0.17)),
    color-stop(0.26, rgba(255,255,255,0)),
    color-stop(0.50, rgba(255,255,255,0)),
    color-stop(0.51, rgba(255,255,255,0.17)),
    color-stop(0.75, rgba(255,255,255,0.17)),
    color-stop(0.76, rgba(255,255,255,0)),
    color-stop(1.00, rgba(255,255,255,0))
  ), -webkit-gradient(linear, left bottom, left top, color-stop(0, #74d04c), color-stop(1, #9bdd62));
  background: -moz-repeating-linear-gradient(top left -30deg,
    rgba(255,255,255,0.17),
    rgba(255,255,255,0.17) 15px,
    rgba(255,255,255,0) 15px,
    rgba(255,255,255,0) 30px
  ), -moz-linear-gradient(#9bdd62 0%, #74d04c 100%);
  -webkit-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
  -moz-box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
  box-shadow: inset 0px 1px 0px 0px #dbf383, inset 0px -1px 1px #58c43a;
  border: 1px solid #4c8932;
  -webkit-animation: animate-stripes 2s linear infinite;
}

Save your ui.css file and view progress.html in your web browser, and you’ll see your gorgeous progress bar, done without using any image.
So, what’s inside? Let me explain the code a bit.

First, we have two CSS classes: .ui-progress-bar and .ui-progress. The first is the container, and the second is the green progress bar.

  • Lines 1 to 9: These lines define a webkit-specific animation, which allows us to move an element from a pint to another.
    For more details about webkit animations, see http://webkit.org/blog/324/css-animation-2/.
  • Line 16: The border-radius CSS3 property allows you to define a radius and get rounded corners.
  • Line 17: Mozilla specific property for border-radius.
  • Line 18: Webkit specific property for border-radius.
  • Line 19: The -webkit-gradient property allows you to add a gradient to an element. It works only on Webkit, other browsers will ignore this property.
  • Line 20: Mozilla specific property, similar to -webkit-gradient with a different syntax.
  • Lines 21 to 23: box-shadow (and its browser specific alternatives) allows you to add a shadow to an element.
  • Line 34: Webkit specific property, based on the standard background-size property, which allows you to specify the size of a background image.
  • Line 56: Triggers webkit animation defined on line 1.

Final touch: Using jQuery to animate the progress bar

A pure CSS3 progress bar is a very cool thing, but progress bars are here to show progress, so we have to animate it. We’re going to use jQuery to do so.

Open your progress.html file and paste the two line below just above the closing</body> tag.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="progress.js" type="text/javascript" charset="utf-8"></script>

This code will load jQuery from Google (Which I recommend to do instead of loading your own copy) as well as your progress.js file, which will contain the required code to animate the progress bar.

Now, paste the code below in your progress.js file:

(function( $ ){
  $.fn.animateProgress = function(progress, callback) {
    return this.each(function() {
      $(this).animate({
        width: progress+'%'
      }, {
        duration: 2000, 

        easing: 'swing',

        step: function( progress ){
          var labelEl = $('.ui-label', this),
              valueEl = $('.value', labelEl);

          if (Math.ceil(progress) < 20 && $('.ui-label', this).is(":visible")) {
            labelEl.hide();
          }else{
            if (labelEl.is(":hidden")) {
              labelEl.fadeIn();
            };
          }

          if (Math.ceil(progress) == 100) {
            labelEl.text('Done');
            setTimeout(function() {
              labelEl.fadeOut();
            }, 1000);
          }else{
            valueEl.text(Math.ceil(progress) + '%');
          }
        },
        complete: function(scope, i, elem) {
          if (callback) {
            callback.call(this, i, elem );
          };
        }
      });
    });
  };
})( jQuery );

$(function() {
  $('#progress_bar .ui-progress .ui-label').hide();
  $('#progress_bar .ui-progress').css('width', '7%');

  $('#progress_bar .ui-progress').animateProgress(43, function() {
    $(this).animateProgress(79, function() {
      setTimeout(function() {
        $('#progress_bar .ui-progress').animateProgress(100, function() {
          $('#main_content').slideDown();
        });
      }, 2000);
    });
  });

});

Save the file, and view progress.html in your web brower: Wow, the progress bar is now animated. How cool is that?

This Javascript code makes the progress bar go from 0 to 100, and then, it displays a message, which is simply “Hello World” in our tutorial.

I hope you enjoyed reading this tutorial as much as I enjoyed writing it. Have fun with CSS3!

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

How to create a kick-ass CSS3 progress bar

How to show a different number of posts for a WordPress category

I used this tip on a category that’s very image intensive to show only 5 posts rather than 10 posts per page. This allowed me to reduce page load times on this category page, whilst still leaving the rest of the website easy to browse.

Open up archive.php and add the following code before the loop.

<?php
            // If showing just 5 gadgets per page
            if (is_category('Gadget Gallery')) {

                // Get the query URL used to show posts from a certain category
                // based on the URL used by the user.
                global $query_string;

                // Show only 5 posts per page (rather than 10 by default) for anything
                // in this category, but respect all pagination and category selection.
                query_posts($query_string . '&posts_per_page=5');
            }
        ?>

<?
// Example loop (no need to copy and paste this)
if ( have_posts() ) : while ( have_posts() ) : the_post();
 ..
endwhile; else:
 ..
endif;
?>

And then after the loop, just paste this:

<?php
	// Reset Query so rest of website doesn't break.
	if (is_category('Gadget Gallery')) {
		wp_reset_query();
	}
?>

You can use any of the conditional tags to determine when to show more or less pages, I chose to use the function that checks for a category by name. I hope it comes in useful!

Thanks to Dan Harrison of WP Doctors for the tip!

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

How to show a different number of posts for a WordPress category

How to use WordPress shortcode outside in your theme files

Simply use the do_shortcode() function anywhere in your theme file. The shortcode you want to use have to be given to the function as shown below:

<?php do_shortcode('[gallery]'); ?>

That’s all :)

Recipe initially published on CatsWhoCode.

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

How to use WordPress shortcode outside in your theme files

Best practices for modern Javascript development

Use the correct <script> tag

When you have to use some Javascript in an html file, you should always use the following <script> tag:

<script type="text/javascript">
    ... some JS code
</script>

But instead, how many times have you seen this when looking at the source code?

<script type="text/javascript" language="javascript">
    ... some JS code
</script>

In HTML, the language attribute is deprecated due to its redundancy with the type attribute. You should never use it anymore.

Keep your code in an external file

Using an external .js file for your Javascript code is a lot cleaner than writing it in your html document, and it also allows the browser to cache the file, which will result in a faster website.

Put your Javascript code in a .js file, then use the <script> tag in your html document to import the file:

<script type='text/javascript' src='http://www.catswhocode.com/myscript.js'></script>

Don’t wrap code in HTML comments

In the 90′s some very old browsers weren’t able to interpret Javascript. In order to prevent unwanted results on those browsers, it was considered good practice in 1994-1997 to wrap Javascript code within html comments, so browsers with no Javascript support will simply ignore it.
Here is an example of some code wrapped within html comments:

<script language="JavaScript">
<!--
...some code
//-->
</script>

However, in 2010, all browsers (Even IE6, that means a lot) can interpret Javascript, so there’s absolutely no need to wrap code within comments anymore. Even worse, if code is wrapped within comments and use the decrement symbol --, you’ll expect some weird problems due to the fact the browser may think it’s the end of the html comment.

Use a framework

Unless your Javascript code is really short and easy, you should always avoid reinventing the wheel by using a framework of your choice. In my opinion, jQuery is the best and has an awesome community, so you should give it a try if you haven’t already.

Always declare your variables using var

You should introduce any variable you create with the var statement, otherwise it gets to the global scope. Also, using var makes your code more readable and self-explanatory.
Example of variable created using the var statement:

var name = "Jean";
var size = data.length;

Keep your code unobtrusive

Some years ago, when a programmer wanted to add an event to an html element (for example, if you want to validate a date when the user typed something) he simply put Javascript code in the html, using a special attribute such as onblur, onchange, onclick, etc.
Example:

<input type="text" name="date" onchange="validateDate()" />

This works great, but it is a bit dirty. HTML should only contain the document description. Just like it’s bad practice to use inline CSS styles, it’s bad practice to use inline Javascript.

Instead, what about using some unobtrusive Javascript? Using jQuery, it is pretty easy to do, as you can see in the following example:

$(document).ready(function(){
	$('input[name=date]').bind('change', validateDate);
});

Include your scripts at the bottom of your HTML files

Not so long ago, it was generally considered good practice to insert your Javascript files within the <head> and </head> tags of your html document.
But browsers read html files from top to bottom, and load external files dynamically. Which mean that inserting scripts within the <head> and </head> tags will make your Javascript load before some of the page content.
In order to always load scripts after the content, Javascript files should always been included at the bottom of your html files, as shown below:

    <script src="myscript.js?" type="text/javascript"></script>
  </body>
</html>

Use JSLint

JSLint is a web-app which takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate solution.
JSLint is great to find bugs in your code, and also things that may be written in a better way. This site is definitely my favorite coding buddy when developing some Javascript.

Don’t use document.write

The good old document.write method has been deprecated for years, however it is still very common to see it while browsing code.

document.write("hello world");

Instead of using this deprecated method, you should use the DOM and the innerHTML function to insert text on a page:

document.getElementById('hello').innerHTML('hello world');

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

Best practices for modern Javascript development

WordPress hack: Remove autolinks in comments

To remove automatic linking of urls in comments, simply open your functions.php file and paste the following:

remove_filter('comment_text', 'make_clickable', 9);

That’s all! Once saved, you can say bye bye to spammy links in comments.

This recipe has been initially published on CatsWhoCode. Don’t forget to read CWC’s list of 10 new WordPress hacks!

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

WordPress hack: Remove autolinks in comments

10 useful new WordPress hacks

Remove comments autolinks

If someone leaves a comment containing a url, the url will be automatically transformed to a link by WordPress. This can be useful, but personally I don’t like to see many links in comments, especially when they’re a bit spammy.
This is why I decided, on the latest CWC theme, to remove comments autolink. Doing so is pretty easy, just paste the following into your functions.php file. Once you saved the file, you’ll notice that autolinks have disappeared.

remove_filter('comment_text', 'make_clickable', 9);

» Source: http://www.wprecipes.com/wordpress-hack-remove-autolinks-in-comments

Automatically notify your users of new posts

If you run a private site using WordPress, then it could be useful to notify your users when a new post is published. The following snippet will get all user emails from your database and will send an email to them automatically when a post is published.
Of course, you shouldn’t use that code on your blog as it does not currently have any unsubscribe option.

function email_members($post_ID)  {
    global $wpdb;
    $usersarray = $wpdb->get_results("SELECT user_email FROM $wpdb->users;");
    $users = implode(",", $usersarray);
    mail($users, "New WordPress recipe online!", 'A new recipe have been published on http://www.catswhocode.com');
    return $post_ID;
}

add_action('publish_post', 'email_members');

Twitter style “time ago” dates

Displaying dates using the “5 days ago” format is becoming very popular on blogs, thanks to Twitter popularity.
I have seen lots of complicated tutorials to use this format on your WordPress blog, however many people don’t know that WordPress has a built-in function to do the same thing: human_time_diff().

Paste the snippet below anywhere within the loop, and it will display your dates using the “time ago” format.

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

» Source: http://www.phpsnippets.info/display-dates-as-time-ago

Display post thumbnail in your RSS feed

Introduced in WordPress 2.9, the the_post_thumbnail() function is very useful to easily add and display a thumbnail attached to a post. Unfortunately, there’s no built-in way to display this thumbnail on your RSS feed.

Happily, the function below will solve this problem. Simply paste it in your functions.php, save it, and the post thumbnail will be automatically displayed on your RSS feed.

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

» Source: http://digwp.com/2010/06/show-post-thumbnails-in-feeds/

Block external requests

By default, WordPress does some external requests in order to get the available updates and the WordPress news shown in your dashboard. Personally, I don’t mind them, but I’ve recently had clients who didn’t wanted any external requests. So, I’ve blocked them using this interesting hack.
Simply add the following line to your wp-config.php file:

define('WP_HTTP_BLOCK_EXTERNAL', true);

If you need to allow some external requests, it it easy to create a whitelist, as shown below:

define('WP_ACCESSIBLE_HOSTS', 'rpc.pingomatic.com');

This line of code have to be pasted in wp-config.php as well.
» Source: http://digwp.com/2010/08/pimp-your-wp-config-php/

Easy debug mode

When things go wrong, you can always use the super useful WordPress debug tool, WP_DEBUG. By default, you have to paste a line of code in your wp-config.php to make the debug mode available.
By if you need to easily access the debug mode even when your site is live, you should edit your wp-config.php file and replace

define('WP_DEBUG', true);

by:

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

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

http://www.catswhocode.com/blog/about?debug=debug

Of course, for obvious security reasons you should replace the name debug by a random word of your choice so no one will ever see your site in debug mode.
» Source: http://yoast.com/wordpress-debug/

Use WordPress shortcode in theme files

WordPress shortcodes are a super easy way to add content such as rss feeds, google maps, galleries and more into your posts or pages. But what about being able to output shortcodes in your theme files?
A built-in function exists, but most people never heard of it. The function is called do_shortcode(). It takes one parameter, the shortcode you’d like to display. I’ve heard you can ad more than one shortcode as a parameter, but I haven’t tried it yet.

do_shortcode('

');

» Source: http://codex.wordpress.org/Function_Reference/do_shortcode

Allow upload of more file types

If you ever tried to upload some not so common filetypes, such as Textmate’s .tmCommand to your WordPress blog, you may have experienced an error, because WordPress simply doesn’t want you to upload some other file type.
Fortunately, you can add new file types to WordPress whitelist. Doing so is quite easy, just paste the following piece of code in your functions.php, and you’re done.
Note that file types have to be separated by a pipe.

function addUploadMimes($mimes) {
    $mimes = array_merge($mimes, array(
        'tmbundle|tmCommand|tmDragCommand|tmSnippet|tmLanguage|tmPreferences' => 'application/octet-stream'
    ));

    return $mimes;
}

add_filter('upload_mimes', 'addUploadMimes');

» Source: http://www.wprecipes.com/wordpress-tip-allow-upload-of-more-file-types

Google Docs PDF viewer shortcode

Google Docs is definitely the easiest way to read documents in .pdf, .doc or .xls online. So, if you want to share a PDF file with your readers, what about creating a shortcode that will open the PDF in Google Docs instead of forcing download?

Simply paste the code in your functions.php.

function pdflink($attr, $content) {
	return '<a class="pdf" href="http://docs.google.com/viewer?url=' . $attr['href'] . '">'.$content.'</a>';
}
add_shortcode('pdf', 'pdflink');

Once you saved the file, you’ll be able to use the shortcode on your posts and page. Here is the syntax:

[pdf href="http://yoursite.com/linktoyour/file.pdf"]View PDF[/pdf]

» Source: http://www.wprecipes.com/wordpress-tip-create-a-pdf-viewer-shortcode

Detect the visitor browser within WordPress

Well, this hack is not so new, but it still remains one of my favorites. What this code does is pretty simple, it detects the name of the visitor browser and adds it to the body_class() function.
That way, you can correct browser-specific problems extremely easily. The function has to be pasted in your functions.php file.

add_filter('body_class','browser_body_class');
function browser_body_class($classes) {
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

	if($is_lynx) $classes[] = 'lynx';
	elseif($is_gecko) $classes[] = 'gecko';
	elseif($is_opera) $classes[] = 'opera';
	elseif($is_NS4) $classes[] = 'ns4';
	elseif($is_safari) $classes[] = 'safari';
	elseif($is_chrome) $classes[] = 'chrome';
	elseif($is_IE) $classes[] = 'ie';
	else $classes[] = 'unknown';

	if($is_iphone) $classes[] = 'iphone';
	return $classes;
}

The function output will look like:

<body class="home blog logged-in safari">

» Source: http://www.nathanrice.net/blog/browser-detection-and-the-body_class-function/

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

10 useful new WordPress hacks

How to set a maximum word count on post titles

To apply this hack, simply paste the following in your functions.php file:

function maxWord($title){
    global $post;
    $title = $post->post_title;
    if (str_word_count($title) >= 10 ) //set this to the maximum number of words
        wp_die( __('Error: your post title is over the maximum word count.') );
}
add_action('publish_post', 'maxWord');

Thanks to Pippin for this great code!

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

How to set a maximum word count on post titles

WordPress tip: easy upgrades using FTP

Simply add the code below to your wp-config.php file:

define('FTP_HOST', 'ftp.yoursite.com');
define('FTP_USER', 'Your_FTP_Username');
define('FTP_PASS', 'Your_FTP_password');
define('FTP_SSL', true); // If you can use a SSL connection set this to true

Thanks to Jesse for this tip!

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

WordPress tip: easy upgrades using FTP

Top 10 CSS3 buttons tutorials

Super Awesome Buttons with CSS3 and RGBA


» View tutorial

Your own Google buttons using CSS3


» View tutorial

CSS3 Gradient Buttons


» View tutorial

Kick-Ass CSS3 Button


» View tutorial

Pure CSS3 icons


» View tutorial

Extremely fancy CSS3 buttons


» View tutorial

BonBon: Sweet CSS3 buttons


» View tutorial

Realistic Looking CSS3 Buttons


» View tutorial

CSS3 “Aqua” buttons with no images


» View tutorial

Flexible CSS3 toggle buttons


» View tutorial

Building beautiful buttons with css gradients


» View tutorial

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

Top 10 CSS3 buttons tutorials

How to: Automatically notify your members on new posts

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

function email_members($post_ID)  {
    global $wpdb;
    $usersarray = $wpdb->get_results("SELECT user_email FROM $wpdb->users;");
    $users = implode(",", $usersarray);
    mail($users, "New WordPress recipe online!", 'A new recipe have been published on http://www.wprecipes.com');
    return $post_ID;
}

add_action('publish_post', 'email_members');

Once saved, all registered users will receive an email when a new post is published.

This recipe is inspired from an example found in WordPress Codex.

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

How to: Automatically notify your members on new posts

How to increase WordPress memory limit, the easy way

Simply open your wp-config file, located at the root of your WordPress install, and paste the following code in it. Once saved, WordPress will be able to use as much memory as specified.

define('WP_MEMORY_LIMIT', '96M');

Thanks to Jeff Starr for the tip! By the way, did you checked out the new version of his book Digging into WordPress?

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

How to increase WordPress memory limit, the easy way

Enhance your web forms with new HTML5 features

Please note that HTML5 is an emerging technique. These examples are not intended for use on a production site. Results may vary according to browser implementation. Please use Chrome or Safari for best results.

Required fields

Whose ever tried to submit a form and gotten an error message saying that you “forgot” to enter your email address? Probably not a lot of us: In fact, 99 percent of all web forms have at least one field marked as required.

In good ol’ HTML, we had to manually display that a specific field is required, most of the time by using a red asterisk. But with HTML5, you can set up a input field to be required:

<input type="text"  name="client_name" required>

And on the CSS side, something like

input:required {
    border: 1px red solid;
}

will save you a lot of time.

Two similar attributes are also available: optional and invalid. They work exactly as the required attribute explained above.

Placeholders

In a form, an input field always has a label explaining what kind of information is required. While you can currently use the label tag to display a label for a specific text field, HTML5 introduces the placeholder attribute. As shown below, using it is pretty simple:

<input name="firstname" placeholder="Please enter your first name">

The HTML5 placeholder attribute works exactly as the value attribute, except that when the user click on the text field, the placeholder text is automatically removed so the user can easily enter his information.

The placeholder attribute currently works only in safari/webkit. Don’t worry about other browsers though, it is pretty easy to simulate placeholders using javascript:

Autofocus

A new HTML5 attribute is named autofocus. If applied to an element, the element will automatically receive the focus once the page is loaded. This can be seen on some sites and most search engines.

Nothing complicated, just use the syntax below, and remember that in HTML5, there’s no more need for attributes to have a value like in XHTML 1.0.

<input name="search" autofocus>

Email fields

Asking someone’s email on a web form is extremely common because email is still the easiest way to contact someone over the internet. HTML5 introduces a new type for the input element, named email.

<input name="email" type="email">

Pattern attribute

When validating a web form, we have to validate the data entered by the visitor. The new pattern HTML5 attribute allows you to define a regular expression pattern. Only the data that matches the defined pattern will be validated. If the data doesn’t match the pattern, then the form will not be submitted.

This is, in my opinion, an extremely good thing, which will save lots of time to developers when coding forms. Though, remember that you should always validate data on the server side as well.

<input type="text" name="Phone" pattern="^0[1-689][0-9]{8}$" placeholder="Phone" required>

Url fields

Nowadays, many people have a website, blog, or at least a Twitter profile. This is why many web forms offer the possibility to enter an url.

HTML5 introduces a new type for the input element, designed specifically for entering urls:

<input name="url" type="url">

Although I didn’t test it myself, I heard that the W3C validator will raise an error if the value of a url field doesn’t match a proper url structure.

Date pickers

Many businesses are offering an appointment request through their website. In that case, the visitor has to specify the day they would like an appointment. HTML5 introduces the date type for the input element:

<input name="day" type="url">

When clicked, the date attribute will display a date picker so visitors will simply have to choose a date instead of entering it manually. Unfortunately, except in Opera, most browsers don’t have it implemented yet.

Note that a date picker can be implemented on your forms using the following types:

<input type="date">
<input type="datetime">
<input type="month">
<input type="week">
<input type="time">

Isn’t that user friendly? Personally, I can’t wait to implement this in my forms but as I said earlier this isn’t very well implemented in browsers at the time of writing this post. Of course, Javascript is always here to help. On this site I found a simple fallback implementation for the input type=date HTML5 attribute:

var i = document.createElement("input");
i.setAttribute("type", "date");
if (i.type == "text") {
    // No HTML5 native date picker support, use jQuery or your favorite framework to create one.
}

Search boxes

To enhance ease of retrieving information, many websites have implemented their own search engine. HTML5 has created a new type for search fields.

<input name="q" type="search">

For now, the only difference with regular text inputs is that, if you use Safari, the search box will have rounded corners. But maybe interesting functionalities will be implemented in the future. Let’s hope, because right now I have to admit that I don’t really see why we should use this type.

Sliders type and step attribute

HTML5 is also introducing sliders: A new type for the input element, which allows visitors to easily select a number instead of entering it manually.

<input name="number" type="range" min="0" max="10">

The example above allows the visitor to choose a number between 0 and 10. If you want the slider to be incremented/decremented 2 by 2, you’ll have to use one more new attribute: step. Here is an example:

<input name="number" type="range" min="0" max="10" step="2" >

That way, visitors will only be able to select numbers like 0, 2, 4, and so on.

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

Enhance your web forms with new HTML5 features

How to define a minimum word count per post

Copy the function below and paste it into your functions.php file. The code will automatically raise an error if someone try to publish a post which is below the minimum allowed word count, defined on line 3.

function minWord($content){
	global $post;
        $num = 100; //set this to the minimum number of words
	$content = $post->post_content;
	if (str_word_count($content) <  $num)
	    wp_die( __('Error: your post is below the minimum word count.') );
}
add_action('publish_post', 'minWord');

Thanks to Pippin WIlliamson for submitting this great recipe!

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

How to define a minimum word count per post