• Feed RSS

7 Simple Rules: WordPress Plugin Development Best Practices

"We’ve been talking a lot about “Best Practices” here on Wptuts lately. Today, we’ll cover some important best practices for creating a WordPress plugin. From security tips to namespacing tricks, follow these rules and you’ll do no wrong. Whether you’re a budding new plugin developer or a time-tested veteran, these simple rules and suggestions will make you a better developer (and the community will thank you for it!)


Rule 01: Have a Strategy

Yes, a strategy. Try this checklist:
  • Is my plugin just for fun/demonstration purposes or for everyday use in the real world?
  • Am I writing it to contribute to the community, to promote myself or to earn income?
  • Can I afford the time to offer support to users?
  • Have similar plugins already been written? Check the WordPress Plugin Repository.
These questions are important because they impact on how seriously you need to take issues such as coding standards, updates, security, support and documentation. Even if you’re just writing a plugin for your own use or for the use of your colleagues, you need to think hard about how you’re going to go about it so that you don’t make a rod for your own back.

Rule 02: Use Consistent and Clear Coding Standards

Which do you prefer, this?
function parsefile($imagedata,$file){
if(!in_array($imagedata['mime'], array('image/jpeg','image/png','image/gif'))){
 $result['error']='Your image must be a jpeg, png or gif!';
 }elseif(($file['size']>200000)){
 $result['error']='Your image was '.$file['size'].' bytes! It must not exceed '.MAX_UPLOAD_SIZE.' bytes.';
 }
 return $result;
}
Or this?
/*
processes the uploaded image, checking against file type and file size
*/
function parse_file($image_data, $file){

 if(!in_array($image_data['mime'], unserialize(TYPE_WHITELIST))){

   $result['error'] = 'Your image must be a jpeg, png or gif!';

 }elseif(($file['size'] > MAX_UPLOAD_SIZE)){

   $result['error'] = 'Your image was ' . $file['size'] . ' bytes! It must not exceed ' . MAX_UPLOAD_SIZE . ' bytes.';

 }

 return $result;

}
Simple things like consistent spacing, indenting, informative variable naming and succinct comments are a good place to start. That’s the only difference in the examples above. WordPress has an excellent guide to coding standards. If you code to a standard your code will be easier to understand, edit and debug.

Use Namespacing

There are two ways to construct a WordPress plugin: as a bunch of functions or as a class. Keep in mind that the functions in your plugin get thrown into the global namespace with all the other non-namespaced functions, which means that if you have a function named plugin_init then it’s probably going to conflict with the same function written by someone else at some point. The obvious way to fix this issue is to prefix the function name with something unique. I like to use the first letters of my plugin name, so if I had a plugin called My Great Plugin, I would call the above function mgp_plugin_init, and the same for the rest of my functions.
But a better way is to create a class for your plugin, that way all functions will be namespaced under the name of the class and even better, you can now use short, common method (function) names.
class my_class{

 function hello_world(){

   return 'Hello World!';

 }

 function goodbye_world(){

   return 'Goodbye World!';

 }

}
Then you could access your class methods under the its own namespace:
$my_new_plugin = new my_class();

echo $my_new_plugin->hello_world();

echo $my_new_plugin->goodbye_world();

Rule 03: Take Security Seriously

Making your plugin secure is the single most important step to take, but many developers discount security or relegate it to the status of an afterthought. Don’t make that mistake.

Sanitize inputs, escape outputs

You should especially make yourself familiar with:
If you use a function such as wp_insert_post, WordPress will sanitize that data for you. Similarly, if you use the database methods $wpdb->insert or $wpdb->update, WordPress will sanitize the data. But if you choose to access the database more directly with something like $wpdb->get_result, then you should use wpdb->prepare to prevent sql injections of malicious code.
Instead of:
$admin_posts = $wpdb->get_results(
 "SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_author = 1"
 );
You would use:
$admin_posts = $wpdb->get_results($wpdb->prepare(
 "SELECT ID, post_title FROM $wpdb->posts WHERE post_status = %s AND post_author = %d",
 'publish', 1
 ));
In the above example, %s is a placeholder for string input (publish) and %d is a placeholder for numeric input (1). You can use as many placeholders as you need.

Use Nonces for Form and URL Verification

It’s important to know that when a form or url is posted back to WordPress, that it was your WordPress site that actually generated it and not some third party or malicious agent. To take care of this aspect of security, we use nonces. A nonce is a number used once.
For a form, we generate a nonce field using wp_nonce_field that will be included in our form as a hidden field:
wp_nonce_field('my_nonce', 'my_nonce_submit');
Because it’s now a hidden field in our form, it’ll come back to us when the form is submitted. We can then check that the nonce is valid using wp_verify_nonce:
wp_verify_nonce($_POST['my_nonce_submit'], 'my_nonce') )
That will return true if the nonce verifies.
For a url (links in emails, browser urls), you can create a nonced url with wp_nonce_url:
$nonced_url = wp_nonce_url('http://my_site.com?action=register&id=123456', 'register_nonce');
That would create a url like this…
http://my_site.com?action=register&id=123456&_wpnonce=250d696dc6
…which you could send in a registration confirmation email. You would then check the incoming url for a nonce with the same id using the check_admin_referer function and proceed with verification if true.
if($_GET['action'] == 'register'){

 if(check_admin_referer('register_nonce')){

   if(verify_id($_GET['id'])){

     echo 'Registration verified!';

   }

 }else{

   echo 'Registration verification FAILED!';

 }
}

Rule 04: Access Web Services Intelligently

The internet is full of web services providing us with everything from weather forecasts to stock quotes to the latest tweets from Twitter. The most efficient way for a plugin to access remote data is to use the HTTP API which will handle your request in the background, using the most efficient of the five possible remote methods that PHP exposes. It’s like a one-stop shop for webservice access.
This uses the wp_remote_get method (a wrapper function of the HTTP class) to get a page body:
$page_data = wp_remote_get('http://site.com/page');

if($page_data['response']['code'] == 200){

 $body = $page_data['body'];

}
Same with wp_remote_post to login:
$args = array(
 'login' => 'login_name',
 'password' => 'my_password'
 );

$response = wp_remote_post('http://site.com/login', $args);

Rule 05: Internationalization

This doesn’t have to be a big deal but is essential if you want to reach the widest audience possible. At a minimum all you need do is prepare your plugin with the _e() and __() functions and worry about the texdomain afterwards.
It’s all explained very well in this wp.tutsplus article by Tom McFarlin and here at the WordPress codex.

Rule 06: Load Only What You Need

When you go away overnight, you don’t take as much with you as you would if you were going on vacation for a month. So treat your plugin the same way: only load the stylesheets, javascript and other scripts that you need for that page or section of the site. At the very least, don’t load admin scripts on the frontend and vice-versa.
if(is_admin()){

 //load my plugin stuff for the admin pages

}else{

 //load my plugin stuff for the frontend

}

Rule 07: Tidy Up After Yourself

When you activate a plugin, you will see a deactivate link appear in the plugins admin page. But deactivating only stops the plugin from functioning. After deactivation, you then get a delete link. The delete link is the key to tidying up after yourself. It should really be called uninstall.
If you create a file named uninstall.php in the same directory as you plugin, the code in this file will be run when the user clicks delete.
if(defined('WP_UNINSTALL_PLUGIN') ){

 //delete options, tables or anything else

}
The above code checks for the WP_UNINSTALL_PLUGIN constant which WordPress sets when you hit delete. Then you can proceed to delete any options or custom tables that your plugin created when it was activated.

Bonus Tips

Turn on debug

The WordPress debugger will find errors in your code that while they may not crash you plugin should still be corrected to make sure that you’re doing things correctly. So, turn on WordPress debug by placing this in your /wp-config.php:
define('WP_DEBUG', TRUE);

Study the WordPress function library

WordPress often has functions that will solve a programming task in one function that you may have written many lines of code to achieve. Check out the function library to make sure you’re not writing more code than you need to.

Get some peer review

Getting others to look at your code is a strong form of quality control. Other users will find faults that you haven’t noticed in your own testing. Don’t be afraid to post your code: everyone makes mistakes.

Don’t use deprecated functions!

WordPress is full of outdated functions that while still supported for current versions may not be in future releases. You may have used code from an old tutorial. Look it up in the WordPress codex to see if it is marked as deprecated. There will be a link to the newer function.

Use a good WordPress code forum

If you have a problem, ask others. There are plenty of forums for WordPress solutions. One of my favorites is WordPress Answers from the wonderful Stack Exchange network.

Take some pride in your work!

It’s easy to release a plugin with a rider that you take no responsibility for the effects of your code. Now, that’s a necessary given: you can’t be responsible for how your plugin will be used. But you can take a professional pride in how you go about your work. Always do your best. Your reputation will be the better for it."
read more

Changing the Fonts of Your WordPress – Part 2: Theme Integration

"WordPress continually proves itself time, time, and again that it has very few limitations, and is rapidly pushing itself to being, if not the best, but certainly the most versatile CMS available. Out of the box it is certainly not perfect, but you can change it however you want. In the previous tutorial, we went over how to add fonts to your theme via a plugin. Now, we’ll integrate font options directly into the theme’s options.

Again, we will be using Google Web Fonts because it’s easy, fast and, most importantly, free. With Google Web Fonts there is no need to worry about using the proper font formats, everything is handled by Google.

Step 1 Add a Settings Page

First, make sure you have a theme options page. If you don’t know how to make one, I suggest reading Create a Settings Page by Jarkko Laine. In this tutorial, I’m going to assume that you know the basics and build from there. So let’s go into our functions.php file and add a simple typography settings page:
add_action( 'admin_menu', 'my_fonts' );
function my_fonts() {
   add_theme_page( 'Fonts', 'Fonts', 'edit_theme_options', 'fonts', 'fonts' );
}

Step 2 Add the Form

Now that we’ve added a settings page, we have to code the callback function we’re using to render the page itself, which would be typography. All we need is a basic form that shows a dropdown of all the fonts that users can choose from and allow them to change it.
function fonts() {
?>
   <div class="wrap">
       <div><br></div>
       <h2>Fonts</h2>

       <form method="post" action="options.php">
           <?php wp_nonce_field( 'update-fonts' ); ?>
           <?php settings_fields( 'fonts' ); ?>
           <?php do_settings_sections( 'fonts' ); ?>
           <?php submit_button(); ?>
       </form>
   </div>
<?php
}
Okay, we’ve added our fonts form to the page, just some basic settings_fields, but WordPress has no idea. Now we use the admin_init action to initialize our settings and add the callbacks:
add_action( 'admin_init', 'font_init' );
function font_init() {
   register_setting( 'fonts', 'fonts' );

   // Settings fields and sections
   add_settings_section( 'font_section', 'Typography Options', 'font_description', 'fonts' );
   add_settings_field( 'body-font', 'Body Font', 'body_font_field', 'fonts', 'font_section' );
}
All we’re doing here is creating a settings section for our fonts forms and the field for a single font, you can add more if you want, in this tutorial I’m only going over the body tag. Just add more by copying that field and replace body with something else like h1. We also now have a setting called fonts, where we will be storing our font data/options. Let’s go ahead and define the callback functions, font_description and body_font_field.
function font_description() {
   echo 'Use the form below to change fonts of your theme.';
}
function body_font_field() {
   $options = (array) get_option( 'fonts' );
   $fonts = get_fonts();

   if ( isset( $options['body-font'] ) )
       $current = $options['body-font'];
   else
    $current = 'arial';

   ?>
       <select name="fonts[body-font]">
       <?php foreach( $fonts as $key => $font ): ?>
           <option <?php if($key == $current) echo "SELECTED"; ?> value="<?php echo $key; ?>"><?php echo $font['name']; ?></option>
       <?php endforeach; ?>
       </select>
   <?php
}
We have to get the font options that we just made in the init action and the fonts we have available, get_fonts(). Set the current font in the form to whatever is in the options, otherwise it’ll default to Arial. Then, use a foreach loop to go through our array of available fonts. You can also add a description or make it a brief tutorial on how to use it.

Step 3 Getting the Fonts

As you noticed in the previous snippet of code, we need to define the get_fonts() function to retrieve the fonts we need. You can either include the Google Webfonts or just stick with the basic CSS fonts. We’ll just use an array to store all of the fonts, and then distinguish them by their font name. You can do this with any fonts, but for the purposes of this tutorial, we’ll just be using Arial, Ubuntu and Lobster.
function get_fonts() {
   $fonts = array(
       'arial' => array(
           'name' => 'Arial',
           'font' => '',
           'css' => "font-family: Arial, sans-serif;"
       ),
       'ubuntu' => array(
           'name' => 'Ubuntu',
           'font' => '@import url(http://fonts.googleapis.com/css?family=Ubuntu);',
           'css' => "font-family: 'Ubuntu', sans-serif;"
       ),
       'lobster' => array(
           'name' => 'Lobster',
           'font' => '@import url(http://fonts.googleapis.com/css?family=Lobster);',
           'css' => "font-family: 'Lobster', cursive;"
       )
   );

   return apply_filters( 'get_fonts', $fonts );
}
Note: You are not limited to only using Google Webfonts. If you want to use a custom font that is hosted on your FTP or on Amazon S3, then replace @import with @font-face and change the url to where your font file is hosted.

Step 4 Add the CSS

Before you apply any of fonts in your CSS, you should remove all instances of Google Webfonts of in your CSS files. This way when we make the import call to get the Ubuntu font, we’re not wasting an extra 100 ms getting the Lobster font too.
Now that we have all of our fonts set, we have to create a wp_head action that adds the styling to your WordPress. If you are using this script for multiple tags, simply duplicate the code, just changing “body” to whichever tag you’re editing.
add_action( 'wp_head', 'font_head' );
function font_head() {
   $options = (array) get_option( 'fonts' );
   $fonts = get_fonts();
   $body_key = 'arial';

   if ( isset( $options['body-font'] ) )
       $body_key = $options['body-font'];

   if ( isset( $fonts[ $body_key ] ) ) {
       $body_font = $fonts[ $body_key ];

       print_ '<style>';
       echo $body_font['font'];
       echo 'body { ' . $body_font['css'] . ' } ';
       echo '</style>';
   }
}
We start by checking if a font is chosen in our options, if not, then set the font to our default, Arial. Now we print out the style tag, the import statement and our CSS code.

What You Get in the End

This is what you should’ve ended up with:
The final font options page.

Full Source Code

For anyone who is having some trouble putting it all together. Here is the full source code, ready to just paste into the functions.php file:
<?
// Changing the Fonts of Your WordPress - Part 2: Theme Integration
// Tutorial on WP Tuts
// by Fouad Matin
// Please credit this tutorial, by putting a link back to http://wp.tutsplus.com/tutorials/changing-the-fonts-of-your-wordpress-site-part-2-theme-integration/
// Enjoy!
add_action( 'admin_menu', 'my_fonts' );
function my_fonts() {
   add_theme_page( 'Fonts', 'Fonts', 'edit_theme_options', 'fonts', 'fonts' );
}
function fonts() {
?>
   <div class="wrap">
       <div><br></div>
       <h2>Fonts</h2>

       <form method="post" action="options.php">
           <?php wp_nonce_field( 'update-fonts' ); ?>
           <?php settings_fields( 'fonts' ); ?>
           <?php do_settings_sections( 'fonts' ); ?>
           <?php submit_button(); ?>
           </form>
       <img style="float:right; border:0;" src="http://i.imgur.com/1qqJG.png" />
   </div>
<?php
}

add_action( 'admin_init', 'my_register_admin_settings' );
function my_register_admin_settings() {
   register_setting( 'fonts', 'fonts' );
   add_settings_section( 'font_section', 'Font Options', 'font_description', 'fonts' );
   add_settings_field( 'body-font', 'Body Font', 'body_font_field', 'fonts', 'font_section' );
   add_settings_field( 'h1-font', 'Header 1 Font', 'h1_font_field', 'fonts', 'font_section' );
}
function font_description() {
   echo 'Use the form below to change fonts of your theme.';
}
function get_fonts() {
   $fonts = array(
       'arial' => array(
           'name' => 'Arial',
           'font' => '',
           'css' => "font-family: Arial, sans-serif;"
       ),
       'ubuntu' => array(
           'name' => 'Ubuntu',
           'font' => '@import url(http://fonts.googleapis.com/css?family=Ubuntu);',
           'css' => "font-family: 'Ubuntu', sans-serif;"
       ),
       'lobster' => array(
           'name' => 'Lobster',
           'font' => '@import url(http://fonts.googleapis.com/css?family=Lobster);',
           'css' => "font-family: 'Lobster', cursive;"
       )
   );

   return apply_filters( 'get_fonts', $fonts );
}
function body_font_field() {
   $options = (array) get_option( 'fonts' );
   $fonts = get_fonts();
   $current = 'arial';

   if ( isset( $options['body-font'] ) )
       $current = $options['body-font'];
   ?>
       <select name="fonts[body-font]">
       <?php foreach( $fonts as $key => $font ): ?>
           <option <?php if($key == $current) echo "SELECTED"; ?> value="<?php echo $key; ?>"><?php echo $font['name']; ?></option>
       <?php endforeach; ?>
       </select>
   <?php
}
function h1_font_field() {
   $options = (array) get_option( 'fonts' );
   $fonts = get_fonts();
   $current = 'arial';

   if ( isset( $options['h1-font'] ) )
       $current = $options['h1-font'];

   ?>
       <select name="fonts[h1-font]">
       <?php foreach( $fonts as $key => $font ): ?>
           <option <?php if($key == $current) echo "SELECTED"; ?> value="<?php echo $key; ?>"><?php echo $font['name']; ?></option>
       <?php endforeach; ?>
       </select>
   <?php
}

add_action( 'wp_head', 'font_head' );
function font_head() {
   $options = (array) get_option( 'fonts' );
   $fonts = get_fonts();
   $body_key = 'arial';

   if ( isset( $options['body-font'] ) )
       $body_key = $options['body-font'];

   if ( isset( $fonts[ $body_key ] ) ) {
       $body_font = $fonts[ $body_key ];

       echo '<style>';
       echo $body_font['font'];
       echo 'body  { ' . $body_font['css'] . ' } ';
       echo '</style>';
   }

   $h1_key = 'arial';

   if ( isset( $options['h1-font'] ) )
       $h1_key = $options['h1-font'];

   if ( isset( $fonts[ $h1_key ] ) ) {
       $h1_key = $fonts[ $h1_key ];

       echo '<style>';
       echo $h1_key['font'];
       echo 'h1  { ' . $h1_key['css'] . ' } ';
       echo '</style>';
   }
}
?>

Conclusion

By now, you should know how to add a font settings page, get fonts from the Google Webfonts directory, and apply those fonts to the theme. If you have any additional suggestions or questions regarding custom typography, feel free to leave a comment!"
read more

Top WordPress Plugins from CodeCanyon: November Edition

"WordPress is a powerful content management system, and the vast array of plugins available certainly helps. CodeCanyon has long been a great place to find top WordPress plugins. From content and security to galleries and sliders, there’s plenty to choose from. Here’s a quick rundown of some of the most popular WordPress plugins available at CodeCanyon.


1. UberMenu

UberMenu is a user-friendly, highly customizable mega menu ( or mega drop down menu ) WordPress plugin. It works out of the box with the WordPress 3 Menu Management System, making it simple to get started but powerful enough to create highly customized and creative mega menu configurations.

2. uBillboard Slider

uBillboard is a Premium Slider for WordPress. It is a jQuery based slider with a multitude of transitions and options for you to be able to customize it to your needs while not overwhelming you with options you never wanted or needed. Version 3 is a revolutionary release with most of the codebase rewritten from scratch. This has enabled us to integrate many features that you have been requesting during the first year.

3. WordPress Video Gallery

The most advanced stock video gallery in the world! Now as a WordPress plugin!

4. Styles with Shortcodes

This plugin lets you customize content faster and easier than ever before by using Shortcodes. Choose from 100 built in Shortcodes!

5. Lightbox Evolution

Lightbox Evolution is a tool for displaying images, html content, maps, and videos in a “lightbox” style that floats overtop of web page. Using Lightbox Evolution, website authors can showcase a wide assortment of media in all major browsers without navigating users away from the linking page.

6. Font Uploader

This plugin lets you upload your own font files and apply them to any element of your website without requiring a knowledge of html or css.

7. Custom Backgrounds

With WordPress 3.0 a new feature was introduced called custom backgrounds for WordPress themes. This feature gives you the ability to add custom backgrounds on your site, which will give your site a unique touch.

8. WordPress Email Newsletter

Easily send mass emails to your existing wordpress user database.

9. 5 Second Google Maps

Simple Google Maps integration with no API keys, no setup and no code editing.

10. Special Recent Posts

It’s the perfect solution for online magazines or simple blogs and it comes with more than 60+ customization options.

11. Security Ninja

Years of industry’s best practices on security combined in one plugin! Perform 25+ security tests including brute-force attacks.

12. Visual Composer

Add columns/elements with one click, then use your mouse to drag elements around to re-arrange them. Control element width with simple mouse clicking.

13. Foobar Notification Bars

A WordPress plugin for adding great looking notification bars to your site.

14. SocialPop

This plug-in adds social media sharing options under the content section on WordPress Posts and Pages. Currently supports sharing for 26 of some of the most popular social media sites.

15. Estro Slider

We have added a custom admin panel which will allow you to customise all aspects of your slider without having to touch a line of code. Drag n drop arranging of your slides, multiple slider insertion, skin selection, Ken Burns customisation, you name it, we’ve included it.

16. Premium Pricing Tables

WP Mega Tables are the perfect solution for those who are in need of a well designed and more importantly a easy to use pricing table in there wordpress themes.

17. Flip Book

Flip Book WordPress Pluginis based is on XML Flip Book / AS3 one of the three top selling items of all times on ActiveDen . It has been built from scratch. Almost everything you see on the page is easily customizable through the WordPress administration panel – easy installation, no coding skills required.

18. jGallery

The jGallery WordPress Plugin gives you a simple and customizable way to create a gallery on any post, page, or sidebar. You have the option to use widgets, shortcodes, or to manually insert your gallery directory into the template files.

19. Ninety Ajax Login/Register

Our Sidebar Login/Register plugin for WordPress does exactly what it says on the tin; Logins and Registrations with a touch of AJAX magic. Simple! It also has a nice ‘logged in’ view, and a lost password form for those forgetful folk.

20. Slider Evolution

Slider Evolution is a JQuery plugin that lets you easily create powerful javascript sliders with very nice transition effects. Enhance your website by adding a unique and attractive slider!"
read more

PHP for WordPress: Mastering Conditional Statements and Tags

"The conditional statements feature is an extremely useful and powerful feature in WordPress; still it remains unused in the development process. You can achieve many things by the simple and smart use of these statements. Sometimes when you need specific text or a unique image to appear on a specific page and not on any other pages in your site, by using conditional statements along with WordPress conditional tags you can achieve this easily without creating multiple pages or templates.


What are Conditional Statements?

PHP “If” statements are generally known as conditional statements. These statements are used within WordPress Theme files along with certain WordPresss functions defining the logic to inform the WordPress database what and how the content should be displayed based on a given criteria. These statements are very important in defining WordPress themes and are similar to creating template hierarchy.
Basic Conditional Statements look like this:
<?php if ( ) { ?>......<?php  } ?>
In layman’s terms, this is pretty simple:
If “something” exists/happens/etc., Do something.
You can (and probably will) use this type of general “if” statement inside WordPress all the time. WordPress has it’s own set of conditional statements as well though, so let’s take a peek at what those look like:

A List of Important WordPress Conditional Tags

Different types of Conditional Tags exist within Conditional Statements. These tags fetch particular information from the WordPress database. These conditional tags are defined for many different items in WordPress e.g. posts, tags, texts, images, categories etc.
Some of the most popular ones are-
1.is_page() - If you want to apply a certain condition to one of your specific page, e.g. “Contact Us” page. You can use this tag to refer to that page using its database ID number or title or slug/name. For instance:
is_page(’2')
or
is_page(‘Contact”)
2. is_category() – If you want to apply a certain condition to a specific category page e.g. Books, then this tag can be used to refer to that page using its database ID number or title or slug/name. For instance:
is_category(“4”) 
3. is_home() – This is used to refer to your home page.
4. is_single() – This is used for single page blogs, single posts or attachments.
5. is_tag() – This is used to refer to a tag archive page. It works similar to category page.
6..is_archive() – This is used to refer to archived pages.
7. is_search() – This is used to refer to search results pages.
8. is_404() – This is used to refer to a HTTP 404: Not Found error page.
9. is_author() – This is used to refer to an author archived page.
10. is_comments_popup() – This is used to refer to a comment popup window.
You can get the complete list of tags on the WordPress Codex page.

Learning by Example

This is all fine and well in theory, but let’s dig into some practical code examples of these conditional statements in action.

Example #1:

What should be the code to display an image on your first page, nothing on the second and some text on the third page? (These pages are hypothetical, you can replace them with your own page names, like Contact Us, About, Information, etc…)
<?php  if ( is_page('First_Page') ) { ?>
 <img src="image.gif" />
 <?php  } elseif ( is_page('Third_Page') ) { ?>
 <p>Here is some text….</p>
 <?php  } else { ?>
 <?php  } ?> 
Please Note-
These codes should be written in your writable theme editor on the page.php file where you want the conditional content to appear.
Extra Note: This is a multi-conditional statement (see the multiple “if, elseif, else…” running logic?) This code checks for the appropriate page using the tags and then displays the items accordingly. You can use unlimited conditions within a code.
is_page(array(‘First_Page’,’Second_Page’)) can be used to display something on both the pages.

Example #2:

How to display a text on either a single post OR a particular category page?
Here you need to use the “||” symbol to display something if any one of the given condition is met. If no condition is satisfied, it displays nothing.
<?php  if(is_category(Category_Page) ) || ( is_single(Single_Page))  { ?>
 <p>Display  this text….</p>
 <?php  } else { ?>
 <?php  } ?>
 
Extra Note: We used the “||” here, which checks for any of the conditions… Alternatively, we could use the “&&” to create an AND condition, in which both the condition must be met in order to display the item. The “!” is used for excluding something from the list.
E.g. !( is_page(Excluded_PageName)). You can also use variables to refer to the sub pages of a parent page. E.g. post->post_parent=="Parent_Page_Name"

Example #3:

How to load other items like CSS files, Java Script files in one of my pages?
This code snippet will show you how to display contact form files only on your Contact Us page.
<?php  if ( is_page( 'contact_us_page' ) ) {   ?>
 <link  rel='stylesheet' href='/contactusform.css' type='text/css' media='all' />
 <script  type='text/javascript' src=k'/jqueryform.js'></script>
 <script  type='text/javascript' src='/spec_forms.js'></script>
 <?php  } ?>

Example #4:

How to use conditional tags in your custom post types?
The mixture of custom post types and conditional tags makes a smart way to display information to the users. The following code snippet will enable you to display contact information at the end of your review posts.
<?php  if ( review_entry' == get_post_type() ) { ?>
 <div  id="reviewcontact">
 <p>If  you're impressed by the  reviews, kindly  contact us asap. Give us a call or <a href="/contact"  title="Contact Us">CLICK HERE</a> to send us a message!</p>
 </div>
 <?php  } ?>

Example #5:

How to check if a “post thumbnail” image has been uploaded or not?
The following code checks for an image and display another if not found.
<?php  if(posted_thumbnail()) {
 show_thumbnail();
 }  else {?>
 <img src="<?php  bloginfo('template_directory');?>/images/default_Image.gif" alt="Image not Displayed">
 <?php  }?>

Conclusion

Thus by mastering these little conditional tags and mixing them with php conditional statements, you can write less and do more in your WordPress site. This not only helps you during the maintenance of your site but it also helps to take advantage of the highly useful WordPress database architecture.
If you guys want to see more of these “basic PHP” tutorials for WordPress, let us know in the comments!"
read more

Load jQuery From Google CDN With Local Fallback For WordPress

"In this tutorial we are going to cover why loading jQuery from the Google CDN with a local file fallback is important, and how to set this up for WordPress. If you’re still trying to self-host your own copy of jQuery (or lots of other script libraries for that matter!), this is a great way to quickly improve your workflow.


Introduction

When I first took a look at HTML5 Boilerplate there was this great code snippet for loading jQuery from the Google CDN with a local file fallback.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script>window.jQuery || document.write("<script src='js/libs/jquery-1.6.4.min.js'>\x3C/script>")</script>

This was the greatest thing I’d seen on the topic of loading scripts for a while… Unfortunately, this doesn’t play well with WordPress, because we should be loading our JavaScripts using wp_enqueue_script, which we recently looked at in this article on using enqueue to properly load scripts inside WordPress.

So, here’s a way to accomplish the same thing in WordPress.


Why Use a Local Fallback File?

Why would I use a local fallback file at all?

The first reason for using a local file fallback is for your local development environment. Internet access isn’t always available when you’re working on your project. Let’s say you work for a web development firm and the companies internet server goes down. If you’ve been working on a script that is jQuery dependent, and you’ve been calling jQuery from the Google CDN. Well, you’re out of luck. Even if you have jQuery cached, eventually you’ll have to clear the cache to make sure the site is rendering properly, or switch to another browser to check cross compatibility.

At that point, you might as well take a long lunch. Which I’m sure your manager won’t be too pleased with. If you’re getting paid by the hour, no internet access isn’t an excuse for not working.

The same could be said if you were at home and the internet went down… or if you traveled to the latest WordCamp and couldn’t get internet access in your hotel. There’s nothing more annoying than being in the zone and having to stop just because you can’t load jQuery.

The second reason is what if Google goes down. Besides the usual rioting in the streets, airplanes falling from the sky, and a plague of frogs. Your site will break, and we can’t have that. The rest we can deal with. Just find a, out of the way, cave and cook up some frog legs.

Seriously though, it’s not likely that Google will ever go down. Google is so big that I’m sure they have backup servers for their backup servers, but you never know. Isn’t better to have a backup of you own, just in case?


Step 1 Where to Start

The script is going to be placed in you functions.php file.

The first thing we need to do is define some variables

<?php
$url = 'http://ajax.googleapis.com/ajax/libssss/jquery/1.6.4/jquery.min.js'; // the URL to check against
$test_url = @fopen($url,'r'); // test parameters
?>

$url is the URL the script is going to use to test against. In this case, we’re testing is the jQuery file on the Google CDN.

$test_url is setting up the parameters for the test.


Step 2 Setting up the Test

Now, let’s set up the main part of the test

<?php
if($test_url !== false) { // test if the URL exists
   //load the external script
} else {
   //load the local script
}?>

if($test_url !== false) is testing to see if it can open the URL we defined in the variable $url. If it can it will load the external script on the CDN. Else, if can’t open the URL it loads the local script on your server.


Step 3 Loading the External Script Function

Here we add the function to load the external CDN file

if($test_url !== false) { // test if the URL exists
   function load_external_jQuery() { // load external file
       wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery
       wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'); // register the external file
       wp_enqueue_script('jquery'); // enqueue the external file
   }
 add_action('wp_enqueue_scripts', 'load_external_jQuery'); // initiate the function
}
  • wp_deregister_script deregisters the default jQuery that comes with WordPress. It’s usually an older version, so I like to use the the most recent version.
  • wp_register_script registers the external CDN jQuery with WordPress.
  • wp_enqueue_script will enqueue the newly register version.
  • add_action will initiate the function.

Step 4 Loading the Local Script Function

An else statement is used to load the local file is the test isn’t able to open the external CDN file

else {
   function load_local_jQuery() {
       wp_deregister_script('jquery'); // deregisters the default WordPress jQuery
       wp_register_script('jquery', bloginfo('template_url').'/js/libs/jquery-1.6.1.min.js', __FILE__, false, '1.6.4', true); // register the local file
       wp_enqueue_script('jquery'); // enqueue the local file
   }
 add_action('wp_enqueue_scripts', 'load_local_jQuery'); // initiate the function
}

This works the exact same way as the external file function. It deregisters the default jQuery, registers the local file, enqueues the local file, and initiates the function.


The Whole Script

Here’s the completed script

<?php
$url = 'http://ajax.googleapis.com/ajax/libssss/jquery/1.6.4/jquery.min.js'; // the URL to check against
$test_url = @fopen($url,'r'); // test parameters
if($test_url !== false) { // test if the URL exists
   function load_external_jQuery() { // load external file
       wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery
       wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'); // register the external file
       wp_enqueue_script('jquery'); // enqueue the external file
   }
 add_action('wp_enqueue_scripts', 'load_external_jQuery'); // initiate the function
} else {
   function load_local_jQuery() {
       wp_deregister_script('jquery'); // initiate the function
       wp_register_script('jquery', bloginfo('template_url').'/js/libs/jquery-1.6.1.min.js', __FILE__, false, '1.6.4', true); // register the local file
       wp_enqueue_script('jquery'); // enqueue the local file
   }
add_action('wp_enqueue_scripts', 'load_local_jQuery'); // initiate the function
}
?>

This Works with Other Libraries Too!

If jQuery isn’t your cup of tea, there’s a CDN for that as well. Be sure to check out the entire hosted scripts library that Google keeps track of: http://code.google.com/apis/libraries/devguide.html . You can load everything from MooTools to Prototype in pretty much the same way that we’ve described above.


jQuery 1.7 Is Out!

Since writing this article, jQuery 1.7 has been released onto the Google CDN. (that’s a lie, we were promised this by November 7th, but we’re still in a holding pattern). Consider the MediaTemple CDN location instead if you want the latest and greatest version of jQuery for your WordPress projects: http://code.jquery.com/.


Conclusion

You can never be too careful and this script will alleviate of your worries about the jQuery library loading.

This can be expanded to include additional CDN resources. You can just add additional URL variables and else statements for additional CDN’s. You can also modified this to do the same test for your own CDN if you use it to load your CSS stylesheets."

read more

5 Cardinal Sins of WordPress Theme Development

"We talk alot on this site about tips and tricks for getting what you want out of WordPress… but today we’re going to take a step back from the technical stuff to look at some practices, bad habits, and coding faux pas that would be better left in our past. So, forgive the heavy-handed post title (haha!), we’re about talk bring up 5 surprisingly common practices that are blemishes on the platform.
Two of the nicest things about working on WordPress Themes is that fact that we get to target in an incredibly flexible environment (that is, the web) and we have solid documentation to help guide us through the process (that is, the WordPress Codex).
After all, if the theme works, does clean, maintainable code matter?
But there’s a danger that exists in theme development, too: we can completely forgo best practices for working with the web and completely ignore the documentation. Specifically, there’s nothing that forces us to write clean, maintainable code. After all, if the theme works, does clean, maintainable code matter? Furthermore, why go through the effort of following WordPress best practices if the theme appears to work fine?
Weak arguments, right? I don’t know – the more I’ve worked in the WordPress space, the more I’ve been surprised which how much bad code actually exists. As such, I thought it would be fun to outline five cardinal sins of WordPress Theme Development.

Ignoring The WordPress Codex

As with most programming languages, frameworks, or libraries, WordPress includes a massive amount of documentation. The WordPress Codex is arguably the best resource that developers have for working with WordPress. After all, it provides documentation for the majority of the application.
But the WordPress Codex often goes above and beyond standard documentation – in addition to supplying function names and parameters, the Codex provides rich examples for how to use many of the API functions. After reading any given article, you’d be hard pressed not to find a clear example of how to the function in question.
In addition to the API, the Codex also features a variety of other articles related to development:
Whenever I’m working on a theme or a plugin and I hit a point where I think I need to write a custom function to achieve something, I’ll search the Codex first. The majority of the time, a function is already available that helps with what I need.
Every serious WordPress Developer should regularly use the Codex when working on any WordPress-related development project. Ignoring it can often lead to creative, but untested and unstable solutions that can cause more harm down the line than good.

Not Localizing Your Theme

A few years ago, if you were to ask me my thoughts on localizing a WordPress Theme, I would’ve said that it would depend on the marketing that you’re targeting. That is, if you think the audience is going to use a language other than your own, definitely do it; otherwise, there’s nothing wrong with leaving the theme translated in your own language.
Fast forward a few years and WordPress’ is powering millions of sites on the Internet. Sites all over the world are using the application to drive their site’s content. On top of that, it’s becoming increasingly common for developers to supplement their income or even make a living off of working with WordPress.
Because WordPress has been so widely adopted and because the Internet has made the world so flat, the market for any given theme is not limited to a single language. On top of that, WordPress makes it so incredibly easy to localize your theme and it requires so little extra effort, that I now argue that localizing your theme is no longer optional.
For the most part, you need to understand three things:
Other than that, there’s very little extra overhead that comes with localizing a theme; however, I do recommend that you take a look at the Translating WordPress article in the Codex. It outlines the three things above and goes more in-depth on each.

Theme File Disorganization

Developers talk a lot about code organization and maintainability. Personally, I think that it’s much easier to give lip service to those principles than actually follow through with them, but they are important.
The thing is, they look different for each project type. Some applications are written in a single language and run on a desktop, some applications use two languages and run on a mobile device, other projects – such as WordPress Themes – can use anywhere from three (HTML, CSS, and PHP) to four (through JavaScript) languages. Additionally, certain components of the theme run on the client side, some run on the server side, some community directly with WordPress, and others communicate directly with the database.
To say that there’s potential to sacrifice maintainability is an understatement.
But it doesn’t have to be problematic as there are certain standards that WordPress suggests for organizing your theme files. Specifically, the Codex details how to organize your PHP template files, your stylesheets, JavaScript sources, and images.
  • Template File Checklist provides a listing of the files that compose a basic a theme and details what each should include.
  • Template Hierarchy provides an explanation for how all of the theme files fit together and how WordPress renders each during its page lifecycle.
  • Stepping Into Templates also provides a detailed breakdown of templates and the WordPress page structure for each.
  • Theme Development is a massive article that encompasses everything surrounding theme development.
Sure, it takes a little extra effort organize your files rather than just doing enough to “get it working,” but the dividends payout over time as you begin working on the next version of your theme or as multiple developers begin to work on the same codebase.

Disregarding Coding Standards

Of course, file organization is only part of the development process that affects organization and maintainability. Next, we have to focus on how we actually write the code that resides in our files.
After all, not only should we want to provide well-organized files, but easy-to-follow, standard-compliant code as well. Again, the WordPress Codex provides standard set for the major languages that contribute to a theme’s codebase:
A lot to process, huh? The thing is, spending time familiarizing yourself with all of the above pays dividends over time. Applying these standards at the beginning of development is exponentially cheaper than having to refactor an existing theme or plugin.
Additionally, it results in contributing better code back to the community.

Not Testing Your Work

After a theme has been developed and is ready for release, you should do – at the very least – a single of testing. That is, you should verify that the various styles of post data are formatted correctly, that your theme isn’t using any deprecated functions, or that it’s using any functions incorrectly.
Luckily, the Codex provides a number of suggestions and tools to help make this process much easier.
  • Debug mode helps to iron out any PHP warnings and/or errors
  • The Theme Unit Test is a data file including pre-formatted post data for you to run against your local development environment
  • Theme Check is a plugin that will examine that codebase of your theme and provide notes on what needs to be addressed as well as recommendations for improving the codebase.
Of course, there’s also additional testing you can do such as cross-browser testing, HTML/CSS standards compliance, and so on. The Codex outlines even more testing suggestions in the Theme Testing Process article.

What Are Your Own Pet Peeves?

They say that you often learn from your mistakes and I’ll be the first to admit that during my time with WordPress, I’ve broken every one of these. But, like the rest of the development community, you learn and you begin building better projects with experience.
This is the first of this type of “WordPress culture” articles that we’ll be posting on the site… so share your own experiences below – or better yet, write about them at length and we’ll publish it if it’s great!
That said, this is certainly not the definitive list and I’m sure there’s more to add (we haven’t even touched hacking the core, harassing the database, or hard coding elements that should have options). Drop your own pet peeves in the comments!
What are some of the most annoying, harmful, or unsustainable practices that you’ve come across?"
read more

Quick Tip! 9 Handy WordPress Code Snippets (That You Really Should Know!)

"Here are some short but handy code snippets that may make your life as a WordPress developer a little easier. We’ll cover a little bit of everything, from how to automatically delete posts, how to quickly dish out a post thumbnail, to how to redirect users once they’ve logged in. Open up your text-replacement program and get ready to add a few new shortcuts!

We’ll start off with a few simple one-liners.

1. Hide The Front-End Dashboard Bar

Since v3.1, WordPress has provided a front-end admin bar for all users. Depending on your intent, this can detract from the look of your site. To disable it, use the show_admin_bar function:
show_admin_bar(FALSE);
You can also disable this from your User Profile, but this is especially useful if you’ve got a ton of authors/members on the site and you need to disable the bar altogether.

2. Empty Trashed Posts Automatically

Trashed posts can build up if you forget to delete them permanently. Use this code in /wp-config.php to empty your trashed posts:
define('EMPTY_TRASH_DAYS', 5 );

3. Turn On WordPress Internal Debugger

When you’re developing, you need to see the errors your code is throwing up. Keep in mind that not all errors stop a script from executing but they are errors nevertheless, and they may have strange effects upon your other code. So, turn on WordPress debug by placing this in your /wp-config.php:
define('WP_DEBUG', TRUE);
You may be amazed by what you see in the footer. Remember to turn debugging off when your site is ready to go public. Debug info can be valuable to hackers.

4. Redirect Users After They Login

When a user logs in, they normally get sent straight to their dashboard. This may not be the experience you want your users to have. The following code uses the login_redirect filter to redirect non-administrators to the home page:
add_filter("login_redirect", "subscriber_login_redirect", 10, 3);

function subscriber_login_redirect($redirect_to, $request, $user){ 

 if(is_array($user->roles)){

   if(in_array('administrator', $user->roles)) return home_url('/wp-admin/');

 }

 return home_url();

}
Based on the user’s role, you could send them to any page you like.

5. Show A Default Post Thumbnail Image

Since v2.9, WordPress has provided a post thumbnail image option, just like the images you see here on wp.tutsplus. On the admin post page it’s called ‘Featured Image’. But if you don’t have an image for your post, you can simply call a default image.
Within the loop:
if(has_post_thumbnail()){

 the_post_thumbnail();

}else{

 echo '<img src="' .  get_bloginfo('template_directory') . '/images/default_post_thumb.jpg" />';

}
You could even have a bunch of default images and pick one at random

6. Show “Time Ago” Post Time For Posts And Comments

Instead of: Posted on October, 12, 2011, we can have: Posted 2 days ago.
As used in the loop:
echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';
  • human_time_diff() converts a timestamp value to a friendly form
  • get_the_time() gets the time the post was made, with ‘U’ parameter gets value as a Unix timestamp
  • current_time() gets the current time, with ‘timestamp’ parameter gets value as a Unix timestamp
Use it on comments as well:
echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago';
Or maybe show the regular date/time of the post only if more than a week ago, else show the time ago:
$time_diff = current_time('timestamp') - get_the_time('U');

if($time_diff < 604800){//seconds in a week = 604800

 echo 'Posted ' . human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';

}else{

 echo 'Posted on ' . get_the_date() . ', ' . get_the_time();

};

7. Style Post Author Comments Differently

It’s nice for users to be able to see when the author of a post makes a comment on the post, just like we do here on wp.tutsplus. All we have to do is add a class to the comment wrapper and then style it in the theme.
In order to find which comments are made by the post author, we use this code to output a class name:
if($comment->user_id == get_the_author_meta('ID')){

 echo '<div class="comment_wrapper author_comment">';

}else{

 echo '<div class="comment_wrapper">';

}
We compare the user ID of the comment with the post author ID from get_the_author_meta. If they match, we echo a class of author_comment which we can then style with css.

8. Show User, Post And Comment Info For Your WordPress Site

You can query your WordPress database directly to show handy site info. Put this function in your functions.php and call it anywhere in your template files with get_site_data()
function get_site_data(){

 global $wpdb;

 $users = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users");

 $posts = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->posts WHERE post_status = 'publish'");

 $comments = $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments");

 echo '<p>' . $users . ' members have made ' . $comments . ' comments in ' . $posts . ' posts</p>';

}
This is better than calling some of the native WordPress functions as it counts all post types and only currently published posts.

9. Add A JavaScript File Correctly

WordPress gives us the wp_enqueue_script function so we can add scripts safely.
Say we have a scripts dir under our template dir, and in there we have a script called do_stuff.js. So we have url_to_template_dir/scripts/do_stuff.js
Let’s include our script the right way. This must be included before the wp_head call in your header file:
$script_url = get_template_directory_uri() . '/scripts/do_stuff.js';

wp_enqueue_script('do_stuff', $script_url);
Here we concatenate our script path and name onto the output of the WordPress get_template_directory_uri function. We then enqueue the script by providing a handle (for possible later reference) and the url to our script. WordPress will now include our script in each page.
The real advantage to all of this is that, say our do_stuff script was a jQuery script, then we would also need to have jQuery loaded.
Now, jQuery is included by default in WordPress, and has been pre-registered with the handle jquery. So all we need do is enqueue our jQuery, then enqueue our do_stuff.js, like this:
wp_enqueue_script('jquery');

$script_url = get_template_directory_uri() . '/scripts/do_stuff.js';

wp_enqueue_script('do_stuff', $script_url, array('jquery'));
Note the third parameter to wp_enqueue_script for do_stuff: that tells WordPress that our do_stuff script is dependent on the file with the handle jquery. This is important because it means that jquery will be loaded before do_stuff. In fact, you could have the enqueue statements in reverse order and it wouldn’t matter since defining a script’s dependencies allows WordPress to put the scripts in correct loading order so that they all work happily together."
read more

20+ Tumblr Style WordPress Themes for Efortless Microblogging

"Tumblr style WordPress themes are a great way to deliver short messages and various types of media with minimal effort. They are a huge time saver, making it much easier to do photo-based posts, smoothly embed audio and video. Tumblr style WordPress themes are for those, who are looking to create a fun and lively blog without spending too much time.


Casual (Free)

In one package you can get all the benefits of Tumblr wrapped in the extensiveness of WordPress and Obox functionality. Tumblog functionality allows you to publish images, videos, audio, text, links and quotes just as you do on Tumblr. When a visitor submits a comment to your blog there are no page reloads. That means they can watch a video and comment at the same time.

Casual Tumblr Style WordPress Theme
Express is an iPhone app built to quickly and effortlessly publish images/links/notes and short posts, on the go, to your Obox powered WordPress website. Tweet, Like or share a custom URL with our neat social sharing options for each post that you publish.

Cinch

Cinch is a feature-rich Tumblog theme built for WordPress. Incorporating advanced QuickPress functionality and nice jQuery awesomeness, Cinch is a first choice for microblogging. Posting a variety of multimedia elements is super-easy.

Cinch Tumblr Style WordPress Theme
The theme includes some jQuery wizardry all round and it makes scrolling & navigating so much fun. The theme has 2 widgetized areas in sidebar and also some extra Woo custom widgets (Flickr, Twitter, Adspace, Search). 11 delicious color schemes to choose from, and possible to change color of links and buttons in options panel.

Fast Blog

Fast blog was released last year, but it still remains very popular Tumblr style WordPress theme with tons of positive responses from its users. It’s perfect for quick and easy microblogging thanks to WooTumblog plugin. You can add posts quickly even from a mobile phone.

Fast Blog Tumblr Style Theme
Fast Blog features smooth Twitter and Flickr implementation with very important buffering system to avoid exceeding the requests limit and to speed up page loading. Custom widgets, social media icons, useful shortcodes, working AJAX contact form are all included out of the box.

Elefolio

Elefolio is here to combine Tumblog publishing and portolio feature into single, easy to use theme. Custom post type is used for portfolio and you can also stream images from your Dribbble account. Elefolio will impress any visitor with its simple yet detailed look.

Elefolio Tumblr Style WordPress Theme for Efortless Microblogging
The homepage displays a welcome message to greet your visitors and social media icons are next to it. You can customize the typography, add custom Woo widgets or choose one of the 9 alternative color styles. This theme support the Express App for iPhone, which lets you post images, notes, links and quotes while on the go!

DailyNotes

DailyNotes aka Notes of Life is a very unique WordPress theme that shines out with its magical simplicity. It’s the most elegant medium to share the moments of your daily life, the easy way. Minimal in design, trimmed down to the bare essentials, DailyNotes is for those, who are looking to create a fun and lively personal blog with a little effort.

DailyNotes WordPress Tumblr Theme
The theme is compatible with all the major browsers (Firefox, Opera, Chrome, IE6+ IE7+IE8, Netscape, Safari). It comes in four different color variations. If the default style isn’t to your liking, then try out the Stone, Wooden and Canvas variations. PSD files are included. Custom tumblr-style post types make it easy to share photos, videos, notes, quotes links and audio files at the click of a button.

Minblr

Minblr theme from Themify is another Tumblr style WordPress theme with a liquid and responsive layout that works well on desktop and mobile devices. It means that the layout flows nicely across any display resolution and is supported by all the major browsers.

Minblr WordPress Theme
Minblr theme has 3 different layout styles and 10 colorful skins. It utilizes WordPress 3.1 post formats, but there is also a fallback to the older versions. Custom homepage welcome message is perfect for intros, memorable quotes, personal thoughts.

Auld

Auld’s simplicity is perfect for lazy bloggers who need colorful and vibrant site for super quick publishing without too much effort in polishing their posts. Auld was created by James McDonald and it is being sold at WooThemes marketplace.

Auld WordPress Theme for Microblogging
Auld uses jQuery Masonry plugin to align the post blocks nicely below each other in a two column fashion. The theme has support for Google Fonts and there is a possibility to customize the typography to suit your taste. This theme supports the Express App for iPhone, which lets you post images, notes, links and quotes while on the go!

Abbreviate

Abbreviate theme uses the Wootumblog plugin that empowers your WordPress theme to act like a Tumblr site. 3 unique color schemes with every detail covered. Using TimThumb you never have to worry about resizing your pictures, it is all done automatically.

Abbreviate WordPress Theme for Microblogging
Abbreviate theme is pre-packed with OCMX Live that is an advanced WordPress framework turning your WordPress installation into even more powerful content management system. OCMX has been designed around the WordPress, meaning almost instant familiarity.

Roughprint

The best thing about WordPress post formats is that you are able to classify your posts into categories and that make the best bits of your content very easy to discover. Take advantage of the new WordPress post formats with this very unique tumblog-style child theme for Thesis or Genesis Framework.

Roughprint Tumblog WordPress Theme
This theme utilizes post formats feature in a Tumblog style way with custom presentations of the different formats. All of these formats work right “out of the box” with no need to touch any code. It’s even easy to edit the icons with the included PSD and separate icons folder. This theme utilizes custom fonts (via CSS) to really make the theme stand out.

Grido

Grido is a trendy and responsive Tumblr-like theme that comes with 9 different gradient backgrounds to style the posts. When a browser window is resized the posts are re-stacked in a smooth animation. There is also a list view next to the grid view layout, optional RSS, search form and social network icons.

Grido Microblogging Theme
You can choose a color scheme to reflect the mood of the post or select a different color for each post to make your it look like a wall of sticky notes. There are up to 4 footer columns to include useful widgets.

Tumble Ten (Free)

Tumble Ten is a modified version of the same default Twenty Ten theme with a more Tumblresque style. In order to use Tumble Ten, you must have the Woo Tumblog plugin installed for the Tumblog functions to work.

Tumble Ten Tumblt Style WordPress Theme
The Woo Tumblog plugin allows you to do Tumblr style posting next to the normal blogging. It becomes very easy to add links, quotes, pictures and videos directly from WordPress dashboard. Tumble Ten theme also comes with 3 custom widgets for flickr photos, twitter feed and author’s bio.

Slanted

Slanted is an extremely unique Tumblog WordPress theme with a literally slanted design. This theme has an extensive multimedia support, which makes posting images, video, audio, quotes, notes, links and other multimedia elements super-easy to do.

Slanted Simple Tumblr Style WordPress Theme
Slanted theme supports the Express App for iPhone, so you can post while on the go. It includes jQuery navigation and hotkeys that makes scrolling and navigating so much fun. Also, you can choose from 10 different color schemes.

Salju (Free)

Salju is a vivacious WordPress theme that features falling snowflakes and a snowman. It is very niche specific and could only be used for a Winter season. There are 7 different post types available and a space for 3 different widgets in the footer.

Salju Theme for Microblogging
Salju uses TwentyTen theme as a Framework, so it is only a child theme. It was built for WordPress 3.0 and above, therefore it does support custom drop-down menus and custom post types.

Nimble

If you need something to share various media types and do it in an easy and professional way, Nimble is ideal. It has a custom made audio player and support for video embedding, so your media will surely attract the attention of blog readers.

Nimble Tumblog Style WordPress Theme for microblogging
With WordPress’s built-in post formats, different types of post are distinguished and that makes it easy to focus on a gallery, video, single image, link, etc. Have a quick few Images you want to share? You can add multiple images to a post and they’ll be displayed in a beautiful grid.

My Journey

My Journey works just like Tumblr, only better. Not only that it is perfect for a personal blog or portfolio, but you can even have fun on the run by posting videos, photos, links and more by using Express App, an iPhone app made by WooThemes that can be bought for $4.99 from the apple app store.

My Journey WordPress Theme for Microblogging
MyJourney WordPress theme comes with 1 click auto-install feature that installs demo content into the theme helping you understand how your new theme works. Built-in SEO options, cross browser optimization, thumbnail auto-sizing and other essential features are included.

LightBright

LightBright is one of the Tumblr style WordPress themes that makes it easy to share the moment of your daily life. Using different post types, you are able to add photos, videos, audio files, quotes or links and make your blog lively in a matter of seconds. LightBright comes with four different color variations. If Turquoise isn’t your style, then try switching to the Purple, Green or Black color schemes.

LightBright WordPress Tumblr Theme for Microblogging
This theme utilizes Timthumb to automatically resize your thumbnail images. If you love the format of Tumblr, but you don’t want to give up the versatility of WordPress, this theme is for you. As long as you are a member of ElegantThemes, you can be sure that your theme will always be compatible with the latest version of WordPress.

Retreat

Based on a theme that has become very successful as tumblog theme. Retreat theme is fully packed with easy to use quick publishing tools. It also comes with AJAX-based Twitter widget that updates often, and can track keywords, mentioned there. This theme support the Express App for iPhone.

Retreat WordPress Theme for Effortless Microblogging
Posting a variety of multimedia elements (images, video, audio, quotes, notes & links) is an easy task to do with Retreat. Post to your tumblog from your dashboard, using the amazing new AJAX-powered & WooThemes-exclusive QuickPress functionality that is bundled with this theme. 7 delicious color schemes to choose from and a possibility to change more colors from the options panel.

Wumblr

Fluid and responsive layout that works well on desktop and mobile devices such as iPhone, Android, Blackberry, etc. 9 different post formats including 15 color presets that help customize the look of each post. Clean and SEO friendly markups for better search engine rankings.

Wumblr Tumblr Style WordPress Theme for microblogging
Take full control of your theme with an easy to use theme options panel. Layered Photoshop file is included when you purchase a Developer Package. There are some custom widget including a header widget for social media profiles.

Tumble

The Tumble Theme is another Tumblr style microblogging theme for WordPress. It takes advantage of WordPress post formats, providing a variety of post styles such as video posts, status updates, quotes, galleries and more.

Tumble WordPress Theme for Microblogging
Organic Themes are coded with the developer in mind, providing W3C valid code and clean formatting for easy theme customization. The design is clean, minimal and easily customized. Tumble theme comes with Option Framework, that allows you to customize your theme easily. Gravity Forms are included for quick and easy form building.

Garuda Di Dadaku (Free)

Garuda Di Dadaku is a free Tumblog style WordPress themes brought to you by WPCharity. Actually it is built on the same TwentyTen theme, so it is another child theme. WPCharity tend to use only free graphic resources to build their themes, so you are 100% sure that all the graphic elements within this theme are legally used.

Salju Theme for Microblogging
It was built for WordPress 3.0 and above, therefore it does support custom drop-down menus and custom post types. There are 7 different post types to choose from including rich media formats. Garuda Di Dadaku headings are enhanced with beautiful custom typography.

Blog Writer

Blog Writer is a great option for bloggers who prefer Tumblr style blogging with some extra content to it. It is also perfect for people, who want Tumblr style blogging and professional look for their personal site. Writer comes with 4 different flavors for you to choose from: Fabric, Leather, Wood and Grass.

Blog Writer Tumblr Style WordPress Theme
With ThemeFuse themes there are no more fiddling with server settings and ordinary WordPress installation procedures, because their themes have one click auto install feature that lets you enjoy your coffee while framework auto-installs the theme.

BonPress (Free)

BonPress is another Tumblog style theme that could be perfect for your personal blog. Packed with various post formats, multiple custom widgets for Twitter and Flickr integration. Theme has 4 color styles: blue, black, pink, orange.

BonPress Tumblr Style Theme
The layout of this theme automatically adapts to fit on any screen resolution on desktop and mobile devices. With an advanced WPZOOM options panel, you can easily customize every major detail of your theme.
Tired of common repetitive templates? Want something different, unusual and unique? This carefully selected list of “Creative WordPress Themes” is dedicated to you."
read more

WordPress Cheat Sheets: The Loop Visual Model

"This entry is part 2 of 2 in the series WordPress Cheat Sheets
With the popularity of our old WordPress cheat sheet, we’ve decided to fire up a new batch of these quick pocket guides that you guys n’ gals can download, save to your phones for a fast reference, or even print out and keep next to your desk while you’re working on customizing WordPress to do your bidding. Today’s cheat sheet: The Loop Visual Model!

The Loop is easily one of the most powerful and crucial pieces of WordPress to understand, and while there’s a lot already written about it, it’s also just nice to have a quick reference for the loop in the event that you need a fast refresher.
This is a quick visual model that can be a great helper when trying to wrap your brain around the loop for the first time (or the thirtieth!). It doesn’t include everything that you can possibly do with it (ie: comments.php isn’t even shown), but it’s a simple model that should pair nicely with coded examples.

Don’t Miss…

Don’t miss out on Our Beginners Guide to The_Loop(), or our Advanced Guide to WordPress Queries, which plays right into the content of this cheat sheet.
Oh, and we’ll be doing our best to keep these sheets updated as WordPress grows into new versions, but if you spot an error (or just want to send some love), let us know in the comments!"
read more

How to Sync A Local & Remote WordPress Blog Using Version Control

"Ever wondered how you might use Version Control with WordPress? If you prefer to work on your WordPress projects locally but have to get them to sync remotely, this tutorial is for you. You have probably tried to synchronize between the two setups by manually uploading the changed files and using PHPmyAdmin to export and import your database once changed, and (very likely) broke something in the process. In this tutorial, we are going to automate the syncing process; so you can concentrate on what you are supposed to do instead of wrestling with never-ending migrations.


The Problem

We usually start WordPress development on our local machines. It’s always faster and easier especially when you have a slow internet connection. But there are times when you need to work remotely. You might want to make a small change, fix some padding or simply publish a new post. The modifications are not saved to your WordPress local machine install and that’s when the mess begins.
The mess starts because you may need to release a new version, and since you work locally, changes that you made remotely need to be brought off-line. It’s a real pain. You need to figure out what files you changed and download/FTP them. Sometimes the changes happen in the Database, so you need a special tool like phpmyAdmin to bring the changes.
In the process, you may break something or forget a modification. That’s when everything becomes messy. In this case, you need two things: version control and synchronization. In this tutorial, I’m going to describe the solution that I’m following to organize my development and sync between my local machine and my remote server.

Step 1 Setting Up The Foundation

Explaining The Plan

First, let me explain what we are going to do. Our aim is to sync easily between the remote and local version. You’ll work in which version you please and then makes them identical. To do that, we need first to account for differences between the remote and the local setup.
WordPress stores information about your blog in both static files and your database. Some of this information is relative to your current hosting. That’s why when you upload your whole WordPress directory and replace the remote version, it will not work.
The information is unluckily split into two parts:
  • Static files: WordPress puts your database server information in the wp-config.php file.
  • Database: WordPress puts the site and home page URL in the wp-options table.
For the wp-config.php, we will implement a process that detects if we are in the local or remote server. That way, the same file will work in both environments. For the database, we’ll integrate it with the version control system and update it to match the local or remote host settings.

Integrating Version Control

I use Mercurial for version control. Git is more popular in the web development arena, but in our case they are almost similar: You just need a version control tool.
Pick Mercurial if you are on a Windows machine. It has Tortoise, a user-friendly interface, to manage your repositories. The version control tool must be installed in both your local and remote machines. That being said, you’ll need a dedicated server or a VPS to be able to install the third-party application.
To initialize a repository in Mercurial, type the following in your console
cd /mydev_directory
hg init
hg add
hg commit
In the first line, we change our working directory to the folder that we want to enable version control in. This will be your WordPress directory (where you’ll install WordPress). The next line initializes the repository. The third line tells mercurial to version control all the files in the directory. This will include sub-folders too. The last line creates a new changeset in the directory; your text editor will open, and you’ll be prompted to write a description of this commit.
This tutorial doesn’t cover how to use Mercurial. If you don’t know version control, then you should learn it. That’s an important tool to add to your skills set. Here are a few tutorials that I suggest:
  • Hginit: Definitively the best tutorial on Mercurial, yet.
  • Mercurial on Ubuntu: This tutorial shows how to setup Mercurial on Ubuntu. Useful if you run Ubuntu on your VPS or dedicated server.

Step 2 Setting Up Your Local WordPress Blog

We will make a fresh install of WordPress in our local machine. Download the latest WordPress version, extract it inside an empty directory of your choice in your web server, and install it from your browser or by changing the wp-config.php file.
Now we are going to activate version control in our WordPress directory
cd /testpress
Hg init
Hg add
Hg commit
These commands initialize the repository and create the first changeset. Now, we can simply clone this repository in our server, install WordPress, and be able to sync back and forth between the local and remote distribution.
However, there are differences as we said earlier. Before implementing the syncing process, we need to implement a script that checks where the WordPress installation is running and loads the right settings. The settings that need to be changed are the database information. They are located in the wp-config.php file and WordPress loads them from this file. My local version looks like this
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'test');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'xxxxx');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
Note that I only copied the part that matters. In my remote server, this part should differ slightly
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'user_blog');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'xyxyx');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
The trick is to write some code that detects where WordPress is located. The variable to use is the PHP variable _SERVER["HTTP_HOST"]. The code evaluates the variable and assigns the database settings.
/*
* Unified variables
*/
$user_name = 'root';
$hostname = 'localhost';
$charset = 'UTF-8';
$collate = '';
/*
* Check for the current environment
*/
if ($_SERVER["HTTP_HOST"] === 'onlineqrlab.com') {
 $db_name = 'user_wordpress';
 $password = 'xyxyxy';
} else if ($_SERVER["HTTP_HOST"] === 'localhost') {
 $db_name = 'test';
 $password = 'xxxxxx';
}

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', $db_name);

/** MySQL database username */
define('DB_USER', $user_name);

/** MySQL database password */
define('DB_PASSWORD', $password);

/** MySQL hostname */
define('DB_HOST', $hostname);

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', $chartset);

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', $collate);
In the example above, I only have two parameters that changed: Database name and password. You may have more than that. For example, if you are hosting mySql in an external server, you’ll need to change the host name for your remote server setup. You’d better also limit the access of the WordPress blog to user level with limited capabilities instead of administrator level.
Check that your WordPress local version works. If it did, then you are half done!

Step 3 Syncing The Mercurial Repositories

Setting The Remote Server Repository

You can start now working on your local WordPress installation. Each time you do a major modification make a commit with Mercurial to track the changes. In the remote server, assuming that you have Apache installed, create a new folder where you’ll upload your WordPress repository.
cd /apache
mkdir mywp_repo
cd mywp_repo

Note that these commands should be executed on your remote server. You’ll require SSH access and a command line too. I’m using Putty on Windows to connect to my server. Once our repository is initialized, we can push (upload) and pull (download) changesets from other repositories to keep it up to date. For this process to happen, you’ll need either your local or remote server to publish the repository so you can pull/push from it.
Mercurial web server is missing some important features like access control, authentication and SSL. So it’s unsecure to use it on your remote server. Preferably, you’ll need to run the Mercurial web server locally and pull the changes from the local server to the remote server. To run the Mercurial server, type the following in your local machine:
hg serve
Now you should be able to access your repository from your browser. Type the URL that gets displayed on your command line. Usually, it’s localhost:8000. The repository is also available online. You can access it from any computer connected to the internet using youripaddress:8000.
Hg pull  192.xxx.xxx.xxx:8000
Hg update
But I don’t recommend this method because it’s not secure. There is an easy and secure way to do that. It’s a middle repository hosted by a third-party service. I’m using BitBucket. It has a good and reliable service and also offers bugs tracking and a wiki.
Register and create an account in BitBucket. They offer unlimited private and public repositories with up to 5 users for free. Create a new repository in BitBucket and you should be taken to this page.

BitBucket has HTTPS and SSH support. If your repository is private, as in my case, you’ll need to authenticate with your username and password to be able to push and pull from the repository. After creating your new repository in BitBucket, execute the following commands in your local machine
hg push https://username@bitbucket.org/username/repository
You’ll be asked to provide your password and the repository will get uploaded to BitBucket. After uploading to BitBucket, clone the repository to your remote server.
hg clone https://username@bitbucket.org/username/repository
hg update
Cloning download the files to a new directory (with the name being the same as your repository directory); you can rename this directory. This will make the first step in this section (where we created the WordPress setup directory) rather obsolete.
Think of BitBucket as a middle-man between your computer and your remote host. It’s possible to have your own secure Mercurial server in your remote server, but this is beyond the scope of this tutorial. The advantage is being independant from the middle-man. This allows pushing changes directly to your web server.
So how is this better than FTP?
  1. You don’t have to figure out which files have changed.
  2. It’s more convenient and takes less time.
  3. A lot faster since Mercurial pushes only the files that changed.

Installing The Remote Server Blog

Already tired? Don’t worry, we are almost there. After pulling the repository either from your local machine or BitBucket, you’ll need to run the WordPress install again; this time on the remote server site. Make sure the settings you put in the wp-config.php file we made earlier are correct, and load your WordPress remote site.
You’ll be asked to install your WordPress blog again, that’s because your database is empty. After the install, your WordPress blog is ready. You can make changes in the remote or local version and sync them with Mercurial.
But there still an important issue: The database doesn’t sync with the files. This is important because things like blog posts, comments, plug-in custom tables… will not be the same in the local and remote version. WordPress has an import/export feature. But it’s not useful, since it doesn’t do a real synchronization. What you need is to go to your phpmyadmin, export all your WordPress tables in one side (remote or local) and then go to the other side phpmyadmin and replace the tables.
After doing this, your WordPress databases will become the same. You’ll need to change, however, the site_url row in the wp_options table. This process gets painful as the database gets heavier.

Step 4 Synchronizing The Databases

As we saw earlier, the database is a little bit problematic. It doesn’t get synchronized with the files, is harder to reach, and requires updating two fields each time you synchronize. It’s not fun doing it over and over again. Automation is the solution; actually, that’s our job.
What we need is a script that synchronizes the local and remote databases without breaking anything. The idea that came to my mind is to include the database in the revision control. The database content will be exported to a file that is tracked by the revision control. Each time we pull changes, the database content will be replaced by this file, making our database up-to-date.
Since there are a couple of rows that differ from a host to another (the site url and home page url), we need another mysql script that updates these ones with the right values. Another important thing is conflicts. If you are working and making changes (commits) to both the remote and local version, this will create a conflict. A typical scenario is when you are working and committing to your local version, and someone (online) is adding new content to your blog. I can’t help in this situation, you need to learn about Mercurial (or your revision control system) merging and team work.
To avoid conflicts, make sure that you pull the repository from BitBucket before making changes; and also to commit and push the changes to BitBucket after making them. This will ensure that BitBucket always has the latest version, and you are also working on the latest version.
This step is a little bit sensitive, so make sure you are following the steps carefully. First, I’m going to explain how the end solution works. You are going to have two scripts: push and pull. Depending on your operating system, it’s going to be push.sh and pull.sh (Linux) or push.bat or pull.bat (Windows). I’m using Windows locally, and Linux (Ubuntu) remotly, so this tutorial will cover both operating systems.
The first script will push the changes to the Bitbucket server. When you make some database changes, use the push script to upload the changes to your BitBucket repository. Push will dump the current database to a file (/db/db_sync.sql) that is tracked by the version control system. The file will be pushed along with the other files and uploaded to BitBucket.
The second script will pull the changes from the Bitbucket server. The pull script will also read the (/db/db_sync.sql) file and replace the database. This will update the database with the version you pushed with. Since they have different hostnames, the pull script will modify the necessary fields, namely the site url and home page url.

Pushing to BitBucket

In the remote and local server, create a new directory called “db”. The exported database file will be saved there. In your local server (I’m assuming you are using Windows) create a new file called push.bat. It doesn’t really matter where you put the file (just make sure you are using the right paths). I put the file in the root directory of my WordPress repository.
mysqldump -u username -ppassword database_name > db/db_sync.sql
hg add db/db_sync.sql
hg commit
hg push https://username@bitbucket.org/username/repository
You can remove the “hg add db/db_sync.sql” command after executing the script for the first time. This is only required once.
In the server side (Linux/Ubuntu), things aren’t really much different. The file extension changes from .bat to .sh, and possibly your mySql server username, password and database name. The file content is exactly the same.

Pulling from BitBucket

Pulling is a little bit harder. It requires importing the SQL file, and also changing some critical fields that differs from an environment to another.
In your local machine, create a file called pull.bat
hg pull https://username@bitbucket.org/username/repository
hg update
cd db
mysql -u username -ppassword testpress < db_sync.sql
mysql -u username -ppassword testpress < db.sql
In your db folder, add a file called "db.sql". This file has SQL statements that will do the required changes to match the host settings. You can add more statements if you need to.
USE testpress;
UPDATE wp_options SET option_value="http://localhost/testpress" WHERE option_name="siteurl";
UPDATE wp_options SET option_value="http://localhost/testpress" WHERE option_name="home";
Apart from the file extension, mySql settings and databas namee nothing really changes in the remote server. This is because we are executing programs commands. The commands and their usage is platform agnostic. Make sure that you enter the correct values for the website URL in the "db.sql" file. They should match your blog URL, if you are not sure you can alwyas check the values in the wp_options table.
To run the scripts, in Windows double click the “.bat” file and in your remote server terminal run the command “sh script_name.sh”.

The Process

You should now have 2 executable files in each environment (pull and push). You should also have a sql script (db.sql) which should not get added to version controlling. We can now test our small system.
  1. In your local machine, add a new blog post
  2. Push the changes from your local machine
  3. Pull the changes in the remote machine
  4. Check if the blog is running correctly and the blog post was added
"
read more