Archive

Archive for May, 2012

Fast BuddyPress Development

May 31st, 2012 Comments off

Working with BuddyPress on top of WordPress is a super exciting thing, it adds a whole new dimension to the platform and really demonstrates huge potential.

BuddyPress like other plugins expands on the core functionality WordPress offers. Although it is important as a freelancer or company to recognise that BuddyPress unlike other plugins adds functionality of epic proportions.

This tutorial aims to show you how to demonstrate a proof of concept quickly and functionally without making any best practice cardinal sins.


Introduction

Over the course of this tutorial we will use a combination of PHP, jQuery and WordPress functions to extend BuddyPress far enough to demonstrate a concept.

Working on member profiles we will without any recourse add a link that allows users to visit a member bookmarks area.

The bookmarks area will be populated with a list of bookmarks a member has decided to save whilst browsing any BuddyPress enabled site.

The scope of bookmarks which can be saved will only be applied to WordPress posts for now, however you may look to build on this further and apply it to other areas of a WordPress powered web site that produces a permalink.


Step 1 The Essentials

We will be building upon the bp-default theme today and creating our own child theme. Below is the structure you should have created.

Theme structure
  • style.css – Some additional styles for icons, buttons and lists (this will not be discussed).
  • sidebar.php – We will call our widget from here.
  • header.php – One modification required.
  • functions.php – Register scripts and a apply a filter.
  • _inc/img/ – A number of image files to be used.
  • _inc/js/bookmarks.js – jQuery and AJAX.
  • members/single/home.php – Some PHP logic to enable the template loader.
  • members/single/bookmarks/ajax.php – Used for our AJAX calls.
  • members/single/bookmarks/loop.php – Retrieval of bookmarks via member profiles.
  • members/single/bookmarks/remove.php – Deletion of bookmarks via my member profile.
  • members/single/bookmarks/save.php – Storage of bookmarks via my member profile.
  • members/single/bookmarks/view.php – Hacky bookmark template loader.
  • members/single/bookmarks/widget.php – Called into site sidebar.php.

style.css – Within style.css we need a bare minimum amount of code to allow for theme selection via wp-admin. Let’s do that now.

/*
Theme Name: Bookmark theme
Description: Child theme from bp-default with added support for member bookmarks.
Version: 1.0
Author: WPTuts
Author URI: http://wp.tutsplus.org
Tags: buddypress
Template: bp-default
*/

Tags: buddypress will notify BuddyPress that we are using a BP enabled theme.

Template: bp-default will instruct BuddyPress that when this theme is active to inherit its functionality from the bp-default theme unless a theme file has been modified.

Within sidebar.php we need to load the widget.php.

locate_template(array('members/single/bookmarks/widget.php'), true);

Step 2 functions.php – Register Script

Let’s go ahead and register the bookmarks.js file, it will be required on every page from here on out. In functions.php add the following.

function px_bookmark_scripts() 
	if(!is_admin()) 
		wp_enqueue_script(
			'px-scripts-functions',
			get_stylesheet_directory_uri() . '/_inc/js/bookmarks.js',
			array('jquery'),
			'1.0',
			true
		);
	
}
add_action('wp_enqueue_scripts','px_bookmark_scripts');

wp_enqueue_script accepts 5 parameters.

  1. Handle – Give your script a name.
  2. Source – Path to your script.
  3. Dependencies – Which scripts will your script need to function.
  4. Version – Version number of your script.
  5. In footer – If false your script will be loaded with wp_head. If set to true it will load with wp_footer.

Anchor attached to post

Browsers of our site will be able to add or remove a WordPress post to their bookmarks by clicking an anchor which reads “Add to bookmarks” or “Remove from bookmarks” located to the bottom of each post.

When either anchor is clicked we will use AJAX and make a request to a PHP script. Once executed we will update the sidebar widget.

Should the browser be logged in as a member of the site they can then save any “Lists of bookmarks” which are currently stored within the session and displayed in the widget.

functions.php

function px_bookmark_link() 
	global $post;
	if(@in_array($post->ID, $_SESSION['bookmarks'])) :
		$content .= 'Remove from bookmarks';
	else :
		$content .= 'Add to bookmarks';
	endif;
	return $content;

add_filter('the_tags', 'px_bookmark_link');

This function is called at each iteration of “the loop” by utilising add_filter and the_tags as our hook.

We let WordPress know that within this function we want access to items within $wp_query and consequently $post. This will allow us to retrieve the_id, the_title and the_permalink.

Some logic is applied when this code executes to determine which link to show. If the user already has the item within their current session we will show a “Remove from bookmarks” anchor and vice versa. in_array() allows us to check this.

in_array() will flag notices if error_reporting has that directive, we use the @ symbol to suppress these notices (hacky).

Using the data returned in $post we form two anchors for adding and removing bookmarks (all data attributes important here) to be later used with our AJAX calls in bookmarks.js.

For a full reference of available filters visit the codex.


Step 3 Widget – Proof of Concept

Widget states

Now we have our link in place let’s create the widget which will appear in the sidebar at all times and will be populated or emptied on demand.

The image above reflects the final states of the widget in 3 scenarios.

  1. No bookmarks whilst being logged in or logged out.
  2. Bookmarks currently saved in session whilst not logged in.
  3. Bookmarks currently saved in session whilst being logged in.

The next block of code is placed within widget.php and nested within HTML markup.

if($_SESSION['bookmarks']) :
	foreach($_SESSION['bookmarks'] as $key => $value) :
		$keys[] = $key;
		$start_count = min($keys);
	endforeach;
endif;
for($i = $start_count; $i < $start_count + count($_SESSION['bookmarks']); $i++) :
	if($_SESSION['bookmarks'][$i]) :
		$bookmark = get_post($_SESSION['bookmarks'][$i]);
		echo '
  • '; echo ''.$bookmark->post_title.''; echo '
  • '; endif; endfor;

    When building this project there was a problem with session data that kept cropping up upon output. Some values were being removed but the key was persisting. Setting a $start_count later to be used when printing the session data solved this problem.

    The important thing to note here is how to retrieve items from $_SESSION['bookmarks'] which will be created in the next stage.

    At each iteration we use get_post() to query the WordPress database with the stored integer values in $_SESSION['bookmarks']. Which will return all the human readable data we need.

    if(is_user_logged_in()) :
    	// Show SAVE button
    else :
    	// Show "LOGIN TO SAVE" message.
    endif;
    if($_SESSION['bookmarks']) :
    	// Show CLEAR button
    endif;
    

    This final piece of logic within widget.php determines which buttons and text to show alongside the widget depending on the state of the current session and
    also if the user is logged in or out.


    Step 4 Adding Bookmarks via AJAX

    jQuery is awesome, here we’ll use the delegate method and listen for clicks on our important anchors. We’ll check for the following items being clicked.

    • Anchors with a class of add-bookmark
    • Anchors with a class of delete-bookmark
    • Anchors with a class of clear-bookmarks

    Using hasClass we can test which item has been clicked within the delegate method and serve the desired AJAX call.

    Should you be building this into a larger project please consider using a pubsub pattern.

    var $bookmark_widget = $('#px-bookmarks'),
    	$bookmark_form = $('#px-bookmarks form'),
    	$bookmark_widget_list = $('#px-bookmarks .current-bookmarks'),
    	$empty_widget = $('#px-bookmarks p'),
    	$widget_buttons = $('#px-bookmarks .widget-buttons'),
    	$login_notify = $('#px-bookmarks .login-notify'),
    	// This should be changed to reflect your domain.
    	$ajax_path = 'http://yoursite.com/wp-content/themes/bookmark-theme/members/single/bookmarks/ajax.php';
    

    First log some variables so we are not “splashing around in the DOM” too much. All DOM selectors above are located within widget.php.

    $(".add-bookmark, .delete-bookmark, .clear-bookmarks").delegate(this, 'click', function(e) 
    	e.preventDefault();
    );
    

    We tell jQuery to listen for click on all of the listed classes and via the callback function we will then tell it what to do. The next portions of code to be added will be placed directly after e.preventDefault().

    Using preventDefault() is a smarter way of nullifying the default action when JavaScript is present. Here is some discussion surrounding preventDefault() on Stack Overflow.

    The next portions of code to be added will be placed directly after e.preventDefault().

    var $post_id   = $(this).data('post-id'),
    	$post_name = $(this).data('post-name'),
    	$post_href = $(this).attr('href'),
    	$that 	   = $(this);
    

    Once a user has clicked any of the “important anchors” we need to store the data attribute values which were attached to anchors in Step 2. This will allow us to send and retrieve the data we want.

    The next code can become a little verbose as we will be showing and hiding elements based on which item has been clicked, with that pre-cursor the code below is the
    bare minimum which will function without aesthetics in mind. However please do download the source and look to these lines.

    if($that.hasClass('add-bookmark')) 
    	$.ajax(
    		url: $ajax_path + '?method=add',
    		type: 'GET',
    		data: 'post_id=' + $post_id,
    		success: function(returndata) 
    			if($bookmark_widget_list.children().length === 0) 
    				// Show / hide
    			
    			$bookmark_widget_list.prepend('
  • ' + $post_name + '
  • '); } }); }

    Here we use hasClass to distinguish which item was clicked by using jQuery to search against our clicked item.

    Based on the outcome we setup our AJAX call a little bit differently each time. With the url and data being requested and sent each time changing slightly.

    Notice ?method=add appended to $ajax_path. This is the equivalent of http://site.com/path/to/ajax.php?method=add.

    When adding a bookmark to the current session the only item we need to pass to our PHP code is the id of that post which was stored into the $post_id variable.

    When jQuery receives a successful response we then append that item to the current bookmark list within the widget area as a list item. Using $post_id, $post_name and $post_href here.

    When the page is refreshed the code added to widget.php in step 3 will kick in.

    On line 7 of the last snippet there is a small subroutine within the success method which determines if there are any list items present within the widget area. This is the previously-mentioned-slightly-verbose code which does nothing more than show and hide some DOM elements. It has been removed for readability here on Wptuts+. Moving on…

    if($that.hasClass('delete-bookmark')) 
    	$.ajax(
    		url: $ajax_path + '?method=delete',
    		type: 'GET',
    		data: 'post_id=' + $post_id,
    		success: function(returndata) 
    			if($bookmark_widget_list.children().length <= 1) 
    				// Show / hide
    			
    			$('#bookmark-'+ $post_id).remove();
    		}
    	});
    }
    

    Much like if($that.hasClass('add-bookmark')) here we check for items clicked that have the class of delete-bookmark.

    Once this subroutine has been entered the url in the AJAX call is altered slightly by sending over a different query string. Namely ?method=delete.

    When a successful response is returned we remove that list item from the current bookmarks stored within the widget.

    Applying some logic in the same fashion as the add-bookmark subroutine to determine if the item removed is going to be the final item. Based on this outcome here DOM elements are again shown or hidden.

    if($that.hasClass('clear-bookmarks')) 
    	$.ajax(
    		url: $ajax_path + '?method=clear',
    		success: function(returndata) 
    			// Show / hide
    
    			$('.postmetadata .delete-bookmark').each(function(index) 
    				// Bookmark list cleared, set anchors attached to posts to default.
    				$(this).removeClass().addClass('add-bookmark').html('Add to bookmarks');
    			);
    		}
    	});
    }
    

    The final code snippet here is used to clear all bookmarks within the widget by setting the url query string to a different method and resetting any anchors on the page to the default "Add to bookmarks" to reflect an empty $_SESSION. This is done by utilising jQuery's each method to find all occurrences of the class delete-bookmark (anchor attached to posts using add_filter) and switching it back to the default
    add-bookmark.


    Step 5 PHP Requested via AJAX

    Now we will create the PHP code referenced in the AJAX calls above which will be used to add, delete and clear all bookmarks from the session.

    Within ajax.php we will create the following 3 functions.

    • add_bookmark()
    • delete_bookmark()
    • clear_bookmarks()

    Let's first create add_bookmark()

    function add_bookmark() 
    	$post_id = $_GET['post_id'];
    	if(@!in_array($post_id, $_SESSION['bookmarks'])) :
    		$_SESSION['bookmarks'][] = $post_id;
    	endif;
    
    

    First we store the $post_id previously passed over in bookmarks.js via data: 'post_id=' + $post_id.

    Next we use the in_array function again to determine if this item should be added to the bookmarks session.

    function delete_bookmark() 
    	$post_id = $_GET['post_id'];
    
    	foreach($_SESSION['bookmarks'] as $key => $value) :
    		$keys[] = $key;
    	endforeach;
    	$start_count = min($keys);
    
    	if(@in_array($post_id, $_SESSION['bookmarks'])) :
    		for($i = $start_count; $i < $start_count + count($_SESSION['bookmarks']); $i++) :
    			if($_SESSION['bookmarks'][$i] === $post_id) :
    				unset($_SESSION['bookmarks'][$i]);
    			endif;
    		endfor;
    	endif;
    
    

    Within the delete_bookmark() function we again store the $post_id.

    Using the same technique to output our bookmarks in widget.php a $start_count is established.

    Next we determine if the item passed ($post_id) exists within the bookmarks session via in_array, and unset any values that are matched.

    function clear_bookmark() 
    	session_start();
    	session_unset();
    	session_destroy();
    
    

    Finally the clear_bookmark() function destroys all session data.

    We will need one more piece of code for this file to be complete. Head to the top of the file and add the following.

    session_start();
    
    $method = $_GET['method'];
    
    switch($method) 
    	case "add" :
    		add_bookmark();
    	break;
    	case "delete" :
    		delete_bookmark();
    	break;
    	case "clear" :
    		clear_bookmark();
    	break;
    
    

    We use session_start() to resume the current session. This is crucial here.

    Next we store the method which is sent over with url in our $.ajax calls.

    Based on the current value of $method we call the appropriate function.


    Step 6 Bookmarks on Members Profiles

    Member bookmarks

    The files we will be dealing with for the remainder of this tutorial are listed below.

    • members/single/home.php – This file is a modified version of bp-default/members/single/home.php.
    • members/single/bookmarks/loop.php – Used to retrieve any previously saved member bookmark lists.
    • members/single/bookmarks/remove.php – Used to delete any saved bookmark lists.
    • members/single/bookmarks/save.php – Used to save any bookmark lists stored within the current session.
    • members/single/bookmarks/view.php – Used as a makeshift template loader.

    Inside home.php we will add a list item to the unordered list within the div with an id of item-nav.

    Using the $bp global we can quickly form the URL required.

    global $bp;
    echo '
  • Bookmarks
  • ';

    This is one of smaller sins we make along the road to demonstrate proof of concept. However to re-iterate proof-of-concept and speedy development is the important factor here.

    Should we decide to expand this feature more we would look to using BuddyPress hooks.

    if($_GET['component'] == 'bookmarks') :
    	locate_template(array('members/single/bookmarks/view.php'), true);
    

    Still within home.php we check against the query string which will allow us to serve custom templates.

    if(!$_GET['action']) :
    	locate_template(array( 'members/single/bookmarks/loop.php'), true);
    elseif($_GET['action'] == 'save' && is_user_logged_in() && bp_is_home()) :
    	locate_template(array( 'members/single/bookmarks/save.php'), true);
    elseif($_GET['action'] == 'remove' && is_user_logged_in() && bp_is_home()) :
    	locate_template(array( 'members/single/bookmarks/remove.php'  ), true);
    endif;
    

    Within view.php (our make-shift template loader) we check for 2 actions and if none has been defined we show the list of saved bookmarks.

    Back in step 3 some logic was added to determine which anchors to show within the widget based on the current state of $_SESSION['bookmarks'] and whether or not the user was logged in.

    Let's create a small table in the database which will be used to store a list of bookmarks which correspond to each member.

    DROP TABLE IF EXISTS `bookmarks`;
    CREATE TABLE `bookmarks` (
    	`id` int(11) NOT NULL AUTO_INCREMENT,
    	`user_id` int(11) NOT NULL,
    	`created` date NOT NULL,
    	`post_ids` text NOT NULL,
    	`list_name` text NOT NULL,
    	PRIMARY KEY (`id`)
    )
    

    The MySQL above will create a new table with 5 fields for us to store bookmark data.

    Once created it's time to move into save.php.

    Save list

    Whilst the user is accessing save.php we will present a form with a text input, here the user will be required to give a label to the list of bookmarks he or she would like to save.

    Once a label has been provided we will store each bookmark list as a row within the database (for later retrieval) and clear the current session.

    if(!$_POST['px-bookmark-list-name']) :
    	// Present form asking to give list a name
    	// Stage 1
    elseif($_POST['px-bookmark-list-name']) :
    	// Label supplied store to database.
    	// Stage 2
    endif;
    

    Now within stage 1 of save.php...

    // If form submitted but no label supplied present error.
    if($_POST['submit'] && !isset($_POST['px-bookmark-list-name'])) :
    	echo '

    A label is required.

    '; endif; // Establish the start counter if($_SESSION['bookmarks']) : foreach($_SESSION['bookmarks'] as $key => $value) : $keys[] = $key; endforeach; $start_count = min($keys); endif; // Loop over items and store in hidden form fields. for($i = $start_count; $i < $start_count + count($_SESSION['bookmarks']); $i++) : if($_SESSION['bookmarks'][$i] !== NULL) : $bookmark = get_post($_SESSION['bookmarks'][$i]); echo ''; echo ''; echo ''; echo ''; endif; endfor;

    First we display an error if no label has been supplied.

    Next we use the same technique from widget.php and ajax.php to establish a start counter and iterate over the session data.

    Finally we output some form fields with the help of get_post.

    global $bp;
    
    foreach($_POST['px-post-id'] as $value) :
    	$posts_to_save[] = $value;
    endforeach;
    
    $posts = serialize($posts_to_save);
    

    During stage 2 of save.php we gain access to the $bp global.

    We loop over the $_POST data and store posts to be saved as an array. This is then serialized and stored into the $posts variable.

    $list_name = $_POST['px-bookmark-list-name'];
    
    $query = $wpdb->insert(
    	'bookmarks',
    	array(
    		'user_id'		=> $bp->loggedin_user->id,
    		'created'		=> current_time('mysql'),
    		'post_ids'		=> $posts,
    		'list_name'		=> $list_name
    	),
    	array(
    		'%d',			// user_id
    		'%s',			// created
    		'%s',			// post_ids
    		'%s'			// list_name
    	)
    );
    

    Next we store the label supplied by the user for this bookmark list into a variable and utilise WPDB to insert the row to the database.

    if($query) :
    	echo '
    '; echo '

    List saved.

    '; echo '
    '; session_start(); session_unset(); session_destroy(); else : echo '
    '; echo '

    There was an error.

    '; echo '
    '; endif;

    Finally we check if the query was successful and unset session data, otherwise display an error.


    Step 7 Retrieving and Deleting Bookmarks

    Remember, in view.php when no particular action is set we will load loop.php. In this file $wpdb will be used to retrieve and output any bookmarks lists.

    global $bp;
    $displayed_user = $bp->displayed_user->id;
    $bookmark_lists = $wpdb->get_results( "SELECT * FROM bookmarks WHERE user_id = $displayed_user ORDER BY id DESC");
    

    Using the $bp global the id of the profile being displayed is stored into the $displayed_user variable.

    Next we perform a query against the bookmarks table with the stored $displayed_user as a where condition.

    if($bookmark_lists) :
    	foreach($bookmark_lists as $bookmark_list) :
    		echo $bookmark_list->list_name;
    		$post_ids = unserialize($bookmark_list->post_ids);
    		foreach($post_ids as $post_id) :
    			$bookmark = get_post($post_id);
    			echo ''.$bookmark->post_title.'';
    		endforeach;
    	endforeach;
    endif;
    

    When results are returned they are displayed by looping over the data and outputting accordingly. Here we make use of unserialize to reverse the effects of
    serialize which was used to store bookmarks previously.

    Remove bookmarks

    We can make one more addition to the previous block of code.

    if(is_user_logged_in() && bp_is_home()) :
    	echo 'Delete list';
    endif;
    

    This will add an anchor to the title of each list which when clicked will pass a new action of remove along with the bookmark list id.

    Which leads us to our final stage... Deleting a bookmark list. Open up remove.php and let's finish this off.

    if(isset($_GET['action']) == 'remove' && isset($_GET['id'])) :
    	$list_id = $_GET['id'];
    	global $bp;
    	$user_id = $bp->loggedin_user->id;
    	$query = $wpdb->query("DELETE FROM bookmarks WHERE id = $list_id AND user_id = $user_id");
    
    	if($query) :
    		echo '
    '; echo '

    List deleted.

    '; echo '
    '; else : echo '
    '; echo '

    There was an error.

    '; echo '
    '; endif; endif;

    First we make sure the action is set to remove and there is an id to build a small query with.

    Next we store some user data and run the query. Users should only be able to delete lists that belong to them, using $bp->loggedin_user->id helps us achieve this.

    Finally we serve a message depending on the outcome.


    Conclusion

    Over the course of this tutorial a number of techniques have been applied. Using jQuery, raw PHP, WordPress conventions and BuddyPress we have been able to illustrate a nice feature to be added to your social network site powered by WordPress and BuddyPress.

    Out of the box BuddyPress does not come with a bookmarks manager attached to member profiles and there isn't a plugin out there that functions exactly like this.

    A bookmarks manager is one example but this could be anything.

    The main goal of this tutorial was to illustrate how quickly and effectively you can hi-jack BuddyPress to demonstrate proof of concept.

    With some know-how this could be put together in an evening with little trouble at all. The time commitment is tangible and could be factored into a monthly maintenance contract.

    However if a client desired more features from the bookmarks manager such as a dashboard widget and more in-depth features you would be stepping into the realms of a plugin.

    Data has not been sanitised in this tutorial so please make sure if you are to place this into a "real world" environment, go through a little bit of validation before-hand.

    I hope you have enjoyed this tutorial and any discrepancies you may find please do leave a comment and will do my best to help you through it.

    Original from: http://wp.tutsplus.com/tutorials/plugins/fast-buddypress-development/

    50 New Resources and Tools for Web Developers

    May 30th, 2012 Comments off

    In this web developer round-up we have chosen 50 recently released resources and tools that offer time-saving solutions to many of the development issues you may come across. So, if you are looking for a tool that will check your Javascript, validate your CSS, help you create an image sprite, or a new HTML5 Canvas library, a new CSS dev framework, or even a parallax scrolling library you will find them all here, and much, much more.

    As per usual, and due to its huge popularity, we purposely didn’t include any jQuery-related resources in this post. jQuery needs and deserves its own post, so you should check out last months 40 Recently Released jQuery Plugins if that is what you are looking for.

    This post has been written in collaboration with our sister site CodeVisually.

    Responsive Grid System

    Responsive Grid System

    The Responsive Grid System is a fluid grid CSS framework for fast, intuitive development of responsive websites. Available in 12, 16 and 24 columns with media queries for all standard devices, clearfix, and optional reset.

    Responsive Grid System →

    Gumby 960 Responsive Grid Framework

    Gumby 960 Responsive Grid Framework

    Gumby 960 Responsive Grid Framework →

    Box CSS Framework

    Box CSS Framework

    Box CSS is a framework based on box-sizing: border-box and display:inline-block building principles.

    Box CSS Framework →

    Foldy960 Framework

    Foldy960 Framework

    Foldy960 is a responsive 960 grid, basically a little kit and some extra classes to get you going on making your 960.gs design responsive.

    Foldy960 Framework →

    Css2Less

    Css2Less

    With Css2Less you can quickly convert your old CSS files to fresh new LESS files. As easy as copy/paste.

    Css2Less →

    Codeanywhere Code Editor

    Codeanywhere Code Editor

    Codeanywhere is a code editor in a browser with support for all popular web formats including HTML, PHP, JavaScript, CSS, and XML.

    Codeanywhere Code Editor →

    Responsive IE6

    Responsive IE6

    Responsive IE6 is a small tool to test your media queries on Internet Explorer 6.

    Responsive IE6 →

    Dirty Markup

    Dirty Markup

    Dirty Markup is a web-based tool to tidy and beautify your HTML, CSS & JS code. It combines the power of HTML Tidy, CSS Tidy, JS Beautify, and the Ace editor to effortlessly clean up your messy code.

    Dirty Markup →

    SnipSave

    SnipSave

    SnipSave lets you save snippets of code online for future reference. It features a very easy-to-use interface where you can quickly create, edit and delete code snippets.

    SnipSave →

    RWD Calculator

    RWD Calculator

    RWD Calculator is a simple calculator to help turn your PSD web template into the start of your responsive website. In other words, it turns pixels into percentages.

    RWD Calculator →

    The Responsinator

    The Responsinator

    The Responsinator helps web designers quickly get an indication of how their responsive site will look on the most popular mobile devices.

    The Responsinator →

    Timeline JS

    Timeline JS

    Timeline, as its name suggest, lets you create beautiful timelines that are easy and intuitive to use. It can pull media from different sources, with built in support for Twitter, YouTube, Flickr, Vimeo, Google Maps and SoundCloud.

    Timeline JS →

    CSSO (CSS Optimizer)

    CSSO (CSS Optimizer)

    CSSO is a CSS optimizer – more specifically, a CSS minimizer. Use it to improve and streamline your CSS.

    CSSO (CSS Optimizer) →

    Graphene

    Graphene

    Graphene is a realtime dashboard & graphing toolkit based on D3 and Backbone. It offers a very aesthetic realtime dashboard that lives on top of Graphite (but could be tailored to any back end).

    Graphene →

    Crossfilter

    Crossfilter

    Crossfilter is a JavaScript library for exploring large multivariate datasets in the browser.

    Crossfilter →

    CanJS

    CanJS

    CanJS is a JavaScript framework that makes building rich web applications easy. CanJS’s core supports jQuery, Zepto, Dojo, YUI and Mootools

    CanJS →

    Fixie

    Fixie

    By interpreting your semantic HTML5 tags, Fixie will automagically add the right type of content in the right places. Headings, paragraphs, links, images, sections…

    Fixie →

    Foresight.js

    Foresight.js

    Foresight.js gives webpages the ability to tell if the user’s device is capable of viewing high-resolution images (such as the 3rd generation iPad) before the image has been requested from the server.

    Foresight.js →

    Webshims Library

    Webshims Library

    Webshims lib is a modular capability-based polyfill-loading library, which focuses on accurate implementations of stable HTML5 features.

    Webshims Library →

    dhtmlxSpreadsheet

    dhtmlxSpreadsheet

    dhtmlxSpreadsheet is an open source Ajax spreadsheet widget written in JavaScript and PHP (also available as a plugin for WP, Joomla, etc.) that allows you to quickly add an Excel-like, editable data table on to a web page.

    dhtmlxSpreadsheet →

    heatmap.js

    heatmap.js

    heatmap.js is a JavaScript library that can be used to generate web heatmaps with the html5 canvas element based on your data.

    heatmap.js →

    Kartograph

    Kartograph

    Kartograph is a lightweight framework for building beautiful, interactive vector map applications without Google Maps or any other mapping service.

    Kartograph →

    sigma.js

    sigma.js

    sigma.js is an open-source and lightweight JavaScript library for drawing graphs, using the HTML canvas element. It has been designed to display interactive static graphs exported from a graph visualization software – like Gephi.

    sigma.js →

    Grunt

    Grunt

    Instead of being a chore, creating a new project and performing repetitive but necessary tasks such as linting, unit testing, concatenating and minifying files become trivially easy with Grunt.

    Grunt →

    Live Scratchpad

    Live Scratchpad

    Live Scratchpad lets you evaluate your JavaScript functions in real-time while editing. It will inspect objects or DOM elements manipulated during execution, figure out the code path taken inside the function and directly jump to errors.

    Live Scratchpad →

    jPages

    jPages

    jPages is a client-side pagination plugin that gives you a lot more features comparing to most of the other similiar plugins, such as auto page turn, key and scroll browse and showing items with delay.

    jPages →

    dgrid

    dgrid

    dgrid is a lightweight, modular, and easily extensible grid component that takes full advantage of modern browsers and object stores.

    dgrid →

    SpritePad

    SpritePad

    SpritePad is a web-based tool that lets you create your CSS sprites within minutes. Simply drag & drop your images and have them immediately available as a PNG sprite + CSS code.

    SpritePad →

    smoke.js

    smoke.js

    smoke.js is a very easy to use and flexible framework-agnostic styled alert system for Javascript. It uses CSS animations and background, so there are no images or js animation code making it very lightweight.

    smoke.js →

    Keymaster

    Keymaster

    Keymaster is a simple micro-library for defining and dispatching keyboard shortcuts.

    Keymaster →

    Leaflet

    Leaflet

    Leaflet is a lightweight JavaScript library for mobile-friendly interactive maps. Weighing just 22kb of gzipped JS code, it still has all the features most developers ever need for online maps.

    Leaflet →

    stroll.js

    stroll.js

    stroll.js is a collection of CSS list scroll effects. The style of scroll effect is determined via the class that is set on the list.

    stroll.js →

    Hammer.js

    Hammer.js

    Hammer.js is a JavaScript library for multi-touch gestures, supporting: tap, double tap, hold, drag, and transform.

    Hammer.js →

    skrollr

    skrollr

    Skrollr allows you to animate any CSS property of any element depending on the horizontal scrollbar position.

    skrollr →

    Style Tiles

    Style Tiles

    Style Tiles are a design deliverable (in PSD format) consisting of fonts, colors and interface elements that help you communicate a web products visual brand.

    Style Tiles →

    TypedJS

    TypedJS

    TypedJS helps you save your JavaScript code by sanity checking it.

    TypedJS →

    Underscore.js

    Underscore.js

    Underscore.js is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.

    Underscore.js →

    KineticJS

    KineticJS

    KineticJS is an HTML5 Canvas JavaScript library that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.

    KineticJS →

    Cutter.js

    Cutter.js

    Cutter.js truncates HTML code to limit its length.

    Cutter.js →

    Socialite.js

    Socialite.js

    Socialite provides a very easy way to implement and activate a plethora of social sharing buttons — any time you wish. On document load, on article hover, on any event!

    Socialite.js →

    Opera Mobile Emulator

    Opera Mobile Emulator

    Opera Mobile Emulator →

    Morris.js

    Morris.js

    Morris.js is a lightweight library that uses jQuery and Raphaël to make drawing time-series graphs easy.

    Morris.js →

    dynamo.js

    dynamo.js

    dynamo.js gives offers a simple method to generate dynamic bits of HTML and add subtle effects to your content.

    dynamo.js →

    Intype

    Intype

    Intype is a fast and easy text editor. It has smart select & edit, snippet insertion and management, auto-paired characters, fast syntax highlighting and code-coloring themes.

    Intype →

    Chico UI

    Chico UI

    Chico UI is a free and open source collection of easy-to-use web tools for developers and designers. Built on top of jQuery, these tools brings known interaction patterns for your website taking advantage of HTML5 and CSS3 features.

    Chico UI →

    HTML5 Web Notifications

    HTML5 Web Notifications

    The HTML5 Web Notifications come in two flavors: plain text and HTML. Plain text allows you to customize a couple of parameters, HTML shows any .html file you want as a notification.

    HTML5 Web Notifications →

    EpicEditor

    EpicEditor

    EpicEditor is an embeddable JavaScript Markdown editor with some minor Markdown enhancements such as automatic link creation and code fencing.

    EpicEditor →

    URI.js

    URI.js

    URI.js is a javascript library for working with URLs. It offers a “jQuery-style” API (Fluent Interface, Method Chaining) to read and write all regular components and a number of convenience methods like .directory() and .authority().

    URI.js →

    Retina.js

    Retina.js

    Retina.js is an open-source script that makes it easy to serve high-resolution images to devices with retina displays.

    Retina.js →

    jq-idealforms

    jq-idealforms

    jq-idealforms is a small framework to create awesome responsive forms. It’s been built on top of jQuery and LESS.

    jq-idealforms →

    Spiffing CSS

    Spiffing CSS

    Spiffing allows you to write your CSS and stylesheets in conformance to proper British English (also known as correct English) grammar and spelling regulations.

    Spiffing CSS →

    You might also like…

    15 Responsive CSS Frameworks Worth Considering →
    15 Free WordPress Themes with a Responsive Layout →
    CSS Form Templates, Tools & Services →
    Liquid, Fluid and Elastic Layout Templates, Tools and Frameworks →
    30 Pure CSS Alternatives to Javascript →
    40 Essential CSS Templates, Resources and Downloads →
    50 Free Tools and Apps for Web Designers and Developers →
    CSS3 Compatibility Tools, Resources and References for Internet Explorer →
    50 Useful Tools and Generators for Easy CSS Development →
    50 Fundamental jQuery Controls, Components and Plugins →
    15 Javascript Web UI Libraries, Frameworks and Toolkits →
    20 Awesome jQuery Enhanced CSS Button Techniques →
    15 jQuery Plugins for Better Web Page Element Layouts →
    20 Awesome jQuery Enhanced CSS Button Techniques →
    25 Useful jQuery Tooltip Plugins and Tutorials →



    Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/9SZIXvxEkfU/

    Categories: Web development, Wordpress Tags:

    Important Tips for Managing a New Tech Startup

    May 29th, 2012 Comments off

    The tech scene has recently seen booming innovation more than we’ve ever seen before. Startups inside the industry are full of young talent searching for an audience. And it’s no surprise that the current state of our Internet is managed by such a few top-ranking social networking sites.

    Over time we will adapt to the value of the Internet and how we can connect with any person from all around the world. This opens up a whole new realm for startups to advance with revolutionary ideas on the web and mobile devices. If you are one of these startup guys interested in success, check out some of the tips I’ve offered in this post.

    San Francisco bay at night - featured image

    Defining a Purpose

    Your team must be comfortable sitting down and working towards a common goal. Regardless of if you’re working with 2 people or 10 or even 100, everybody needs to push forward towards one finished product. This purpose should be outlined in advance and give the startup some value.

    Maybe your idea is to revolutionize web hosting with newer green technology. Or building a mobile app for sharing up-to-the-minute news with friends via iOS. Whatever your startup falls into make sure it’s clear, concise, and plausible. Because once everything is in production it’s more difficult to go back and redo major concepts.

    Get the Team on Board

    While discussing your product I should also mention another key point – the team. You need to have everybody who’s working on your product super excited. Not even just excited, but dedicated and passionate about the end result. When you have a passionate team it’s only easier to reach goals and complete tasks month after month.

    The Instagram app - team working in San Francisco, CA

    Typically tech startups revolve around a single type of digital product. This could be Premium WordPress themes or web graphics/icons. But alternatively your team may be working in the realm of social products – such as a new social network or information sharing center. The Internet is all about connecting people, after all.

    Though no matter what you’re doing, it’s evident your company will need some web presence. How else can you market any powerful idea all across the world? Even just a small corporate-style website with a couple pages is much better than nothing at all. And typically this works out well since you won’t need to hire any extra web developers for the task.

    Don’t Try to Reinvent the Wheel

    I notice this all the time with young enthusiastic developers. You look at WordPress and say “I can design a better CMS than this”. And in truth maybe you can – I’ll admit the Admin panel feels bland after looking at it all day long.

    But the startup scene is ferocious and this kind of attitude just won’t work. The reality of the situation is that WordPress can offer everything you’d need for an online magazine, corporate site, even a social networking feature. And going further you have plenty of other options to build off including Joomla!, Drupal, Pligg, Fork CMS, SMF… the amount of open source code is not slowing down. So it’s important that you take advantage of these backend systems, at least during the early launch phase.

    Fork CMS publishing for the web - open source script

    In the long run your startup is a business focused on turning a profit and helping the world. The first year is all about getting a product completed and building a recognizable branding. Take pride in your work, but don’t try going back and re-doing features that are already available at your fingertips.

    Software is easier to build when you use abstraction – basically layers upon layers of pre-determined code. This is why so many app developers can create programs for Windows and Mac without needing extensive knowledge of the Operating System. This case holds true for the Internet as well. You can build a killer website on any of the CMS’ available and slowly create new ideas off their features, without even needing to know all the internal code.

    Move with a Plan

    It’s all too easy falling into a routine schedule every day where each person is working on their own little piece of the project. This is great in the early stages – but after a couple of months it’s important that everybody start working off a master plan.

    iPhone Facebook iOS app icon

    This plan could be a detailed written piece or just a small list of tasks. It should represent all the tasks you need to complete in order of importance. It can be fun to finish off the extra sidebar widget design, but this will not earn you extra money or visitors come end of the day.

    I always say that marketing is truly #1 above all else. A good marketer can sell a horrible website and probably do a half-okay job. Regardless of what your product is, nobody can use it unless they can find links. The Internet is loaded with opportunities for marketing and you should jump on these quickly after launching.

    Along with basic marketing you’ll also have to handle public relations. This includes social networking accounts, answering support e-mails, and dealing with other PR media(interviews, articles, phone convos, etc). There is so much more to consider, but that will all change based on your startup’s goals. Maintenance is very important so don’t get too stressed out if things seem to be moving slowly. Just having your website up online each day is a significant feat in itself!

    Marginalize Failure

    This is always a groundbreaking idea which entrepreneurs find difficult to grasp. Failure is inevitable and always part of life. But failure only becomes reality when you give up and let the failure end everything.

    Facebook Founder Mark Zuckerberg speaking Hacker News Meetup

    I recommend using your experiences with failure as lessons in the grander scheme of things. Even if you wake up to realize your startup idea is fundamentally flawed, you do not need to call it quits. Go back to the drawing board and revamp the idea. Remove what isn’t going to work and start focusing on what you need to do. Just make things happen.

    Because unfortunately nobody else will come in and make things happen for you.

    Conclusion

    The startup world is all about hustling and pushing forward aggressively with your ideas. There is no hard and fast method for building such a profitable company. It often requires years of hard work and dedication to your cause. But startup ideas and small businesses will always be the way of the future, offering regional prosperity and employment options. Try applying these techniques to your own startup vision and you’ll surely come out successful.



    Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/hJn1qNZ__Hw/

    Categories: Web development, Wordpress Tags:

    Data Sanitization and Validation With WordPress

    May 29th, 2012 Comments off

    Proper security is critical to keeping your site or that of your theme or plug-in users safe. Part of that means appropriate data validation and sanitization. In this article we are going to look at why this is important, what needs to be done, and what functions WordPress provides to help.

    Since there seem to be various interpretations of what the terms ‘validation’, ‘escaping’ and ‘sanitization’ mean, I’ll first clarify what I mean by them in this article:

    • Validation – These are the checks that are run to ensure the data you have is what it should be. For instance, that an e-mail looks like an e-mail address, that a date is a date and that a number is (or is cast as) an integer
    • Sanitization / Escaping – These are the filters that are applied to data to make it ‘safe’ in a specific context. For instance, to display HTML code in a text area it would be necessary to replace all the HTML tags by their entity equivalents

    Why Is Sanitization Important?

    When data is included in some context (say in a HTML document) – that data could be misinterpreted as a code for that environment (for example HTML code). If that data contains malicious code, then using that data without sanitizing it, means that code will be executed. The code doesn’t even necessarily have to be malicious for it to cause undesired effects. The job of sanitization is to make sure that any code in the data isn’t interpreted as code – otherwise you may end up like Bobby Tables’ school…

    A seemingly innocuous example might be pre-filling a search field with the currently queried term, using the unescaped $_GET['s']:

    This opens up a vulnerability that could allow javascript to be injected by, for instance, tricking someone into visiting http://yoursite.com?s="/>. The search term ‘jumps’ out of the value attribute, and the following part of the data is interpreted as code and executed. To prevent this, WordPress provides get_search_query which returns the sanitized search query. Although this is a ‘harmless’ example the injected script could be far more malicious and at best it would just ‘break’ the form if search terms contain double quotes.

    How this malicious (or otherwise) code may have found its way onto your site is not the concern here – but rather it is to prevent it from executing. Nor do we make assumptions about the nature of this unwanted code, or its intent – it could have simply been an error on the user’s part. This brings me to rule No.1…


    Rule No. 1: Trust Nobody

    It’s a common maxim that is used with regards to data sanitization, and it’s a good one. The idea is that you should not assume that any data entered by the user is safe. Nor should you assume that the data you’ve retrieved from the database is safe – even if you had made it ‘safe’ prior to inserting it there. In fact, whether data can be considered ‘safe’ makes no sense without context. Sometimes the same data may be used in multiple contexts on the same page. Titles for instance, can safely contain quotes or double quotes when inside header tags – but will cause problems if used (unescaped) inside a title attribute of a link tag. So it is rather pointless to make data ‘safe’ when adding it to the database, since it is often impossible to make data safe for all contexts simultaneously. (Of course it needs to be made safe to add to the database – but we’ll come to that later).

    Even if you only intend to use that data in one specific context, say a form, it is still pointless to sanitize the data when writing to the database because, as per Rule No. 1, you cannot trust that it is still safe when you take it out again.


    Rule No. 2: Validate on Input, Escape on Output

    This is the procedural maxim that sets out when you should validate data, and when you sanitize it. Simply put – validate your data (check it’s what it should be – and that it’s ‘valid’) as soon as you receive it from the user. When you come to use this data, for example when you output it, you need to escape (or sanitize) it. What form this sanitization takes, depends entirely on the context you are using it in.

    The best advice is to perform this ‘late’: escape your data immediately before you use or display it. This way you can be confident that your data has been properly sanitized and you don’t need to remember if the data has been previously checked.


    Rule No. 3: Trust WordPress

    You might be thinking “Ok, validate before writing to database and sanitize when using it. But don’t I need to make sure the data is safe to write to the database?”. In general, yes. When adding data to a database, or simply using an input to interact with a database, you would need to escape the data incase it contained any SQL commands. But this brings me to Rule No. 3, one which flies in the face of Rule No. 1: Trust WordPress.

    In a previous article, I took user input (sent from a search form via AJAX) and used it directly with get_posts() to return posts that matched that search query:

    	$posts = get_posts( array(
    		's'=>$_REQUEST['term']
    	) );
    

    An observant reader noticed that I hadn’t performed any sanitization – and they were right. But I didn’t need to. When you use high-level functions such as get_posts(), you don’t need to worry about sanitizing the data – because the database queries are all properly escaped by WordPress’ internals. It’s a different matter entirely if you are using a direct SQL query – but we’ll look at this in a later section. Similarly, functions like the_title(), the_permalink(), the_content() etc. perform their own sanitization (for the appropriate context).


    Data Validation

    When you receive data entered by a user it’s important to validate it. (The settings API, covered in this series, allows you to specify a callback function to do exactly this). Invalid data is either auto-corrected, or the process is aborted and the user is returned to the form to try again (hopefully with an appropriate error message). The concern here is not safety but rather validity – if you’re doing it right, WordPress will take care of safely adding the data to the database. What ‘valid’ means is up to you – it could mean a valid email address, a positive integer, text of a limited length, or one of an array of specified options. However you aim to determine validity, WordPress offers a lot of functions that can help.

    Numbers

    When expecting numeric data, it’s possible to check if the data ‘is some form of number’, for instance is_int or is_float. Usually, it’s sufficient to simply cast the data as numeric with: intval or floatval.

    If you need to ensure the number is padded with leading zeros, WordPress provides the function zeroise(). Which takes the following parameters:

    • Number – the number to pad
    • Threshold – the number of digits the number will be padded to

    For example:

    echo zeroise(70,4); // Prints 0070
    

    E-mails

    To check the validity of e-mails, WordPress has the is_email() function. This function uses simple checks to validate the address. For instance, it checks that it contains the ‘@’ symbol, that it’s longer than 3 characters, the domain contains only alpha-numerics and hyphens, and so forth. Obviously, it doesn’t check that the e-mail address actually exists. Assuming the e-mail address passed the checks, it is returned, otherwise ‘false’ is returned.

    	$email = is_email('someone@e^ample.com');
    	// $email is set to false.
    
    	$email = is_email('someone@example.com');
    	// $email is set to 'someone@example.com'.
    

    HTML

    Often you may wish to allow only some HTML tags in your data – for instance in comments posted on your site. WordPress provides a family of functions of the form wp_kses_* (KSES Strips Evil Scripts). These functions remove (some subset of) HTML tags, and can be used to ensure that links in the data are of specified protocols. For example the wp_kses() function accepts three arguments:

    • content – (string) Content to filter through kses
    • allowed_html – An array where each key is an allowed HTML element and the value is an array of allowed attributes for that element
    • allowed_protocols – Optional. Allowed protocol in links (for example http, mailto, feed etc.)

    wp_kses() is a very flexible function, allowing you to remove unwanted tags, or just unwanted attributes from tags. For example, to only allow or tags (but only allow the href attribute):

    $content = "Click here to visit  wptuts+ ";
    
    echo wp_kses( $content, array(
    	'strong' => array(),
    	'a' => array('href')
    ) );
    
    // Prints the HTML "Click here to visit  wptuts+ ":
    Click here to visit  wptuts+ 
    

    Of course, specifying every allowed tag and every allowed attribute can be a laborious task. So WordPress provides other functions that allow you to use wp_kses with pre-set allowed tags and protocols – namely the ones used for validating posts and comments:

    The above functions are helpful in ensuring that HTML received from the user only contains whitelisted elements. Once we’ve done that we would also like to ensure that each tag is balanced, that is every opening tag has its corresponding closing tag. For this we can use balanceTags(). This function accepts two arguments:

    • content – Content to filter and balance tags of
    • force balance – True or false, whether to force the balancing of tags
    // Content with missing closing  tag
    $content = "Click here to visit  wptuts+";
    
    echo balanceTags($content,true),
    
    // Prints the HTML "Click here to visit  wptuts+ "
    

    Filenames

    If you want to create a file in one of your website’s directories, you will want to ensure the filename is both valid and legal. You would also want to ensure that the filename is unique for that directory. For this WordPress provides:

    • sanitize_file_name( $filename ) – sanitizes (or validates) the file-name by removing characters that are illegal in filenames on certain operating systems or that would require escaping at the command line. Replaces spaces with dashes and consecutive dashes with a single dash and removes periods, dashes and underscores from the beginning and end of the filename.
    • wp_unique_filename( $dir, $filename ) – returns a unique (for directory $dir), sanitized filename (it uses sanitize_file_name).

    Data From Text Fields

    When receiving data inputted into a text field, you’ll probably want to strip out extra white spaces, tabs and line breaks, as well as stripping out any tags. For this WordPress provides sanitize_text_field().

    Keys

    WordPress also provides sanitize_key. This is a very generic (and occasionally useful) function. It simply ensures the returned variable contains only lower-case alpha-numerics, dashes, and underscores.


    Data Sanitization

    Whereas validation is concerned with making sure data is valid – data sanitization is about making it safe. While some of the validation functions referred to above might be useful in making sure data is safe – in general, it is not sufficient. Even ‘valid’ data might be unsafe in certain contexts.


    Rule No. 4: Making Data Safe Is About Context

    Simply put you cannot ask “How do I make this data safe?”. Instead you should ask, “How do I make this data safe for using it in X”.

    To illustrate this point, suppose you have a widget with a textarea where you intend to allow the user to enter some HTML. Suppose they then enter:

     Hello World
    

    This is perfectly valid, and safe, HTML – however when you click save, we find that the text has jumped out of the textarea. The HTML code is not safe as a value for the textarea:

    What is safe to use in one context, is not necessarily safe in another. Whenever you use or display data you must keep in mind what forms of sanitization need to be done in order to make using that data safe. This is why WordPress often provides several functions for the same content, for instance:

    • the_title – for using the title in standard HTML (inside header tags, for example)
    • the_title_attribute – for using the title as an attribute value (usually the title attribute in tags)
    • the_title_rss – for using the title in RSS feeds

    These all perform the necessary sanitization for a particular context – and if you’re using them you should be sure to use the correct one. Sometimes though, we’ll need to perform our own sanitization – often because we have custom input beyond the standard post title, permalink, content etc. that WordPress handles for us.

    Escaping HTML

    When printing variables to the page we need to be mindful of how the browser will interpret them. Let’s consider the following example:

    Suppose $title = . Rather than displaying the HTML

    In fact, if you are doing this, you should almost certainly be using wp_localize_script() – which handles sanitization for you. (If anyone can think of a reason why you might need to use the above method instead, I would like to hear it).

    However, to make the above example safe, you can use the esc_js function:

    
    

    Escaping Textarea

    When displaying content in a textarea, esc_html is not sufficient because it does not double encode entities. For example:

    text bold' ?>
    
    

    $var printed in the textarea will appear as:

    text bold
    

    Rather than also encoding the & as & in the tags.

    For this WordPress provides esc_textarea, which is almost identical to esc_html, but does double encode entities. Essentially it is little more than a wrapper for htmlspecialchars. In this example:

    text bold' ?>
    
    

    Antispambot

    Displaying e-mail addresses on your website leaves them prone to e-mail harvesters. One simple method is to disguise the e-mail address. WordPress provides antispambot, which encodes random parts of the e-mail address into their HTML entities (and hexadecimal equivalents if $mailto = 1). On each page load the encoding should be different and while the returned address renders correctly in the browser, it should appear as gobbledygook to the spambots. The function accepts two arguments:

    • e-mail – the address to obfuscate
    • mailto – 1 or 0 (1 if using the mailto protocol in a link tag)
    $email = "joebloggs@example.com";
    $email = sanitize_email($email);
    echo ''.antispambot($email).' ';
    

    Query Strings

    If you wish to add (or remove) variables from a query string (this is very useful if you wish to allow users to select an order for your posts), the safest and easiest way is to use add_query_arg and remove_query_arg. These functions handle all the necessary escaping for for the arguments and their values for use in the URL.

    add_query_arg accepts two arguments:

    • query parameters – an associative array of parameters -> values
    • url – the URL to add the parameters and their values to. If omitted, the URL of the current page is used

    remove_query_arg also accepts two arguments, the first is an array of parameters to remove, the second is as above.

    // If we are at www.example.com/wp-admin/edit.php?post_type=book
    $query_params = array ('page' => 'my-bage');
    $url = add_query_arg( $query_params );
    
    // Would set $url to be:
    // www.example.com/wp-admin/edit.php?post_type=book&page=my-page
    

    Validation & Sanitization

    As previously mentioned, sanitization doesn’t make much sense without a context – so it’s pretty pointless to sanitize data when writing to the database. Often, you need to store data in its raw format anyway, and in any case – Rule No. 1 dictates that we should always sanitize on output.

    Validation of data, on the other hand, should be done as soon as it’s received and before it’s written to the database. The idea is that ‘invalid’ data should either be auto-corrected, or be flagged to the data, and only valid data should be given to the database.

    That said – you may want to also perform validation when data is displayed too. In fact sometimes, ‘validation’ will also ensure the data is safe. But the priority here is on safety and you should avoid excessive validation that would run on every page load (the wp_kses_* functions, for instance, are very expensive to perform).


    Database Escaping

    When using functions such as get_posts or classes such as WP_Query and WP_User_Query, WordPress takes care of the necessary sanitization in querying the database. However, when retrieving data from a custom table, or otherwise performing a direct SQL query on the database – proper sanitization is then up to you. WordPress, however, provides a helpful class, the $wpdb class, that helps with escaping SQL queries.

    Let’s consider this basic ‘SELECT‘ command, where $age and $firstname are variables storing an age and name that we are querying:

    SELECT * WHERE age='$age' AND firstname = '$firstname'
    

    We have not escaped these variables, so potentially further commands could be injected in. Borrowing xkcd’s example from above:

    $age = 14;
    $firstname = "Robert'; DROP TABLE Students;";
    $sql = "SELECT * WHERE age='$age' AND firstname = '$firstname';";
    $results = $wpdb->query
    

    Will run as the command(s):

    SELECT * WHERE age='14' AND firstname = 'Robert'; DROP TABLE Students;';
    

    And delete our entire Students table.

    To prevent this, we can use the $wpdb->prepare method. This accepts two parameters:

    • The SQL command as a string, where string variables are replaced by the placeholder %s and decimal numbers are replaced by the placeholder %d and floats by %f
    • An array of values for the above placeholders, in the order they appear in the query

    In this example:

    $age = 14;
    $firstname = "Robert'; DROP TABLE Students;";
    $sql = $wpdb->prepare('SELECT * WHERE age=%d AND firstname = %s;',array($age,$firstname));
    $results = $wpdb->get_results($sql);
    

    The escaped SQL query ($sql in this example) can then be used with one of the methods:

    • $wpdb->get_row($sql)
    • $wpdb->get_var($sql)
    • $wpdb->get_results($sql)
    • $wpdb->get_col($sql)
    • $wpdb->query($sql)

    Inserting and Updating Data

    For inserting or updating data, WordPress makes life even easier by providing the $wpdb->insert() and $wpdb->update() methods.

    The $wpdb->insert() method accepts three arguments:

    • Table name – the name of the table
    • Data – array of data to insert as column->value pairs
    • Formats – array of formats for the corresponding values (‘%s‘,’%d‘ or’%f‘)
    $age = 14;
    $firstname = "Robert'; DROP TABLE Students;";
    $wpdb->insert(
    	'Students',
    	array( 'firstname' => $firstname, 'age' => $age ),
    	array( '%s', '%d' )
    );
    

    The $wpdb->update() method accepts five arguments:

    • Table name – the name of the table
    • Data – array of data to update as column->value pairs
    • Where – array of data to match as column->value pairs
    • Data Format – array of formats for the corresponding data values
    • Where Format – array of formats for the corresponding ‘where’ values
    // Update Robert'; DROP TABLE Students; to Bobby
    
    $oldname = "Robert'; DROP TABLE Students;";
    $newname = "Bobby";
    $wpdb->update(
    	'Students',
    	array( 'firstname' => $newname ),
    	array( 'firstname' => $oldname ),
    	array( '%s' ),
    	array( '%s' )
    );
    

    Both the $wpdb->insert() and the $wpdb->update() methods perform all the necessary sanitization for writing to the database.

    Like Statements

    Because the $wpdb->prepare method uses % to distinguish the place-holders, care needs to be taken when using the % wildcard in SQL LIKE-statements. The Codex suggests escaping them with a second %. Alternatively you can escape the term to be searched for with like_escape and then add the wildcard % where appropriate, before including this in the query using the prepare method. For instance:

    $age=14;
    $firstname = "Robert'; DROP TABLE Students;";
    SELECT * WHERE age=$age (firstname LIKE '%$firstname%');
    

    Would be made safe with:

    $age=14;
    $firstname = "Robert'; DROP TABLE Students;";
    SELECT * WHERE age=$age AND (firstname LIKE '%$firstname%');
    $query = $wpdb->prepare('SELECT * WHERE age=%d AND (firstname LIKE %s);', array($age, '%'.like_escape($firstname).'%') );
    

    Summary

    This isn’t an exhaustive list of the functions available for validation and sanitization, but it should cover the vast majority of use cases. A lot of these (and other) functions can be found in /wp-includes/formatting.php and I’d strongly recommend digging into the core code and having a look into how WordPress core does validation and sanitization of data.

    Did you find this article useful? Do you have any further suggestions on best practices for data validation and sanitization in WordPress? Let us know in the comments below.

    Original from: http://wp.tutsplus.com/tutorials/creative-coding/data-sanitization-and-validation-with-wordpress/

    Weekly Design News – Resources, Tutorials and Freebies (N.134)

    May 29th, 2012 Comments off

    This is our weekly column were we share our favorite design related articles, resources and cool tidbits from the past week. Enjoy :)
    If you would like to receive our daily updates and keep up to date with the latest and greatest articles and resources from the design community, you can follow us on Twitter, on Facebookor by subscribing to our RSS feed.

    Our Weekly Design News has been sponsored by MediaLoot. Check them out for some seriously useful resources like icon fonts, UI kits, vectors and themes.

    HTML for Icon Font Usage

    HTML for Icon Font Usage

    Put Users in Control With Confirmation Feedback Buttons

    Put Users in Control With Confirmation Feedback Buttons

    Custom WordPress 404 Page

    Custom WordPress 404 Page

    Gestures-Sensitive Slideshow: Responsive and Touch-Friendly

    Gestures-Sensitive Slideshow: Responsive and Touch-Friendly

    Yahoo! Unveils Axis – A ‘Search’ Browser Enhancement

    Yahoo! Unveils Axis – A 'Search' Browser Enhancement

    Code Poet – New resource from the guys behind WordPress

    Code Poet – New resource from the guys behind WordPress

    Diving into CanJS

    Diving into CanJS

    Create an Upload Form using jQuery, CSS3, HTML5 and PHP

    Create an Upload Form using jQuery, CSS3, HTML5 and PHP

    Animating CSS3 Gradients

    Animating CSS3 Gradients

    Animated 3D Bar Chart with CSS3

    Animated 3D Bar Chart with CSS3

    WordPress Meet Responsive Design (Free Ebook)

    WordPress Meet Responsive Design (Free Ebook)

    GoSocial: A Free Social Media Icon Pack

    GoSocial: A Free Social Media Icon Pack

    Free Icons for a Menu

    Free Icons for a Menu

    Adobe CS6 Replacement Icons

    Adobe CS6 Replacement Icons

    Clear Login Window Template (PSD)

    Clear Login Window Template (PSD)

    Instagram GUI (.psd)

    Instagram GUI (.psd)

    Bariol Regular – Free Font

    Bariol Regular - Free Font

    Infographic – How Tech Savvy Are Today’s Dads?

    Infographic - How Tech Savvy Are Today's Dads?

    How To Choose The Right Face For A Beautiful Body

    How To Choose The Right Face For A Beautiful Body

    This Week on CodeVisually

    Here are our favorite webdev resources from the past week:



    Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/B0csAoMPKh0/

    The ICO Amends the EU Cookie Law to Allow ‘Implied Consent’

    May 28th, 2012 Comments off

    At the last minute, the UK’s Information Commisioner’s Office (ICO) has decided to dilute an already watery law. Last Thursday, among the last minute amendments to the law, legislators added implied consent to the EU Cookie law, which appears to be an appeal to overall acceptance and at odds with the law’s requirements of explicit informed consent.

    After a year of leeway to allow organizations to work towards compliance with the Cookie Law, the ICO has rolled back to previous considerations of implied consent as being “more practical” solution to the explicit and, very visible, opt-in model. In a post on the ICO website, Dave Evans, Group Manager of Business and Industry, offered a summary of the clarifications:

    In short, implied consent is considered a valid form of consent and is considered compliant with the revised cookie rules. To be able to rely on implied consent, it is required that you don’t rely on a complex privacy policy and have users that understand that they are engaged in actions that result in setting cookies. However, the ICO suggests that explicit consent may be warranted in cases of sensitive personal data collection.

    Head of marketing and privacy law at a prominent UK law firm, Stephen Groom, said that the decision to consider implied consent as a valid form of consent was a “striking shift” from previous ICO statements where the ICO said that consumer awareness was not high enough for websites to rely entirely on implied consent, whereas now they stated that “implied consent has always been a reasonable proposition in the context of data protection law.”

    How is the development community responding to this sudden change? With some ire, to put it delicately. Silktide, who had previously created videos on the law’s implementation, expressed some outrage, pointing out: “A year ago you graciously granted us an extra year to comply with the law, announcing your decision just 24 hours before the law came into effect. Last week, 24 hours before the really-we-mean-it-this-time law took hold, you changed it completely.”

    These new guidelines challenge the UK web economy, equally challenging companies from Fortune 500 (Adobe) sizes to those on a smaller scale, such as Speckyboy. These new guidelines prevented this website from executing a planned implementation of the Cookie Law and forces it (and other independent sites) to come up with new lighter solutions.



    Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/Krrte4GhclQ/

    Categories: Web development Tags:

    20 Creative Personal Blog Web Designs

    May 28th, 2012 Comments off

    As clearly and concisely defined by Wikipedia, a blog is ‘a personal journal published on the World Wide Web consisting of discrete entries (“posts”)…’. But when you do read back that definition you soon realize how far we have drifted away from it, especially over the last couple of years and particularly within the design community. Once upon-a-time a blog was a place where you could express your opinions, your thoughts and your ideas. Nothing more, nothing less. Just your personal writing.

    Nowadays though, a blog is viewed as many things (a marketing tool, a means for businesses to communicate with customers, a portfolio, an ecommerce solution, and on, and on…) and very rarely do you come across a new blog that fits into the definition I highlighted above. Yes, I know that the web is continually evolving, and that trends do come and go. But when I was researching this post, I found myself yearning for a bygone era when discovering a new personal blog, especially within the design community, could often be exciting and educational.

    Anyway, back to this post, the good news is that I did manage find 20 blogs, mainly from the design community, that not only do they meet the criteria set out by the Wikipedia definition above, but that are also beautifully and originally designed as well. Just as ‘blogs’ should be.

    Here they are:

    Visual Idiot

    Visual Idiot

    Rivers & Robots

    Rivers & Robots

    Elliot Jay Stocks

    Elliot Jay Stocks

    Trent Walton

    Trent Walton

    Jon Phillips

    Jon Phillips

    Dave Gamache

    Dave Gamache

    Karl Fernandes

    Karl Fernandes

    Stuart Frisby

    Stuart Frisby

    Sacha Greif

    Sacha Greif

    Jean-Philippe Gams

    Jean-Philippe Gams

    Janna Hagan (A Student’s Guide to Web Design)

     Janna Hagan (A Student's Guide to Web Design)

    Hardly Code Blog

    Hardly Code Blog

    Jason VanLue

    Jason VanLue

    Jason Stone

    Jason Stone

    The Mavenist

    The Mavenist

    Tim Van Damme

    Tim Van Damme

    Thomas Aull

    Thomas Aull

    Russ Maschmeyer

    Russ Maschmeyer

    Girl With A Camera – Ashley Baxter

    Girl With A Camera - Ashley Baxter

    Massimo Dutti

    Massimo Dutti

    Osvaldas Valutis

    Osvaldas Valutis

    You might also like…

    40 Examples of Brilliant Responsive Website Layouts →
    30 Highly Unusual Web Designs →
    A Showcase of Typography in Webdesign →
    A Showcase of 50 Amazing Personal Blog Web Designs (2010)→



    Original from: http://feedproxy.google.com/~r/speckboy-design-magazine/~3/PcKlDkaewN4/

    Categories: Web development Tags: ,

    Function Examination: wp_nav_menu

    May 28th, 2012 Comments off

    When WordPress 3 presented us with the new Menus functionality, it changed the way we viewed navigation menus forever. No longer were we bound to using the normal page listing functions or building our own custom menu functions to integrate category and page menus as well as external or hard linked items within a nav menu. But just how custom can we get with this new functionality? In this tutorial, we’ll dive deep into everything that the wp_nav_menu function can do, use the Walker Class to add a sub description, and touch on some of its related functions.


    The Parameters

    The function has several parameters to work with. Here are the defaults as listed in the WordPress.org Codex:

     ,
    	'menu'            => ,
    	'container'       => 'div',
    	'container_class' => 'menu-menu slug-container',
    	'container_id'    => ,
    	'menu_class'      => 'menu',
    	'menu_id'         => ,
    	'echo'            => true,
    	'fallback_cb'     => 'wp_page_menu',
    	'before'          => ,
    	'after'           => ,
    	'link_before'     => ,
    	'link_after'      => ,
    	'items_wrap'      => '%3$s',
    	'depth'           => 0,
    	'walker'          =>
    );
    ?>
    
    
    

    Theme Location

    Using this parameter, we can set a theme location which is then used on the Menus page to set a menu to work in that part of your theme, without having to manually define which menu should appear there. This is very helpful for theme distributors because you’re able to use conditionals to display a menu only if the user has defined a menu for that location. The only other requirement is that you use the function register_nav_menu() to register those locations. This is usually done from your function files when you’re setting up support for menus.

    Let’s start building our custom menu function parameters assuming that we’ve registered a theme location called “primary“.

    $params = array(
    	'theme_location' => 'primary'
    );
    

    Menu

    This parameter is used to manually define which menu should be used. In our example, we are only setting a generic menu location and not defining an exact one to use, but if we were wanting to tell the function to use a menu called “Primary Navigation”, our parameters would look like this:

    $params = array(
    	'theme_location' => 'primary',
    	'menu' => 'Primary Navigation'
    );
    

    Container

    By default, our menu will be wrapped in a div, but if you’re like me, you usually don’t need this and probably want to cut back on the amount of divs and other tags being used to keep your code as tidy as possible. You could also use this parameter to define a different tag such as an html5

    or

    Quick Tip: Your Own Video Shortcode

    May 27th, 2012 Comments off

    You probably use a video embedding plugin or you just use the embed codes of video sites. But there’s a third, easier way to embed videos in your WordPress site: a simple (but useful) video shortcode.


    Why Should I Use a Video Shortcode?

    • Because video embedding plugins are just another little burden for your blog. They take some space on your disk (granted, not more than 1MB), they always query your database for their options and you need to learn how to use the plugins.
    • Because embedding the codes of the video sites can be corrupted – especially when you switch between the WYSIWYG editor and the HTML editor.
    • And most importantly: Because shortcodes are awesome! They’re easy to use, they can have the functionality of many plugins and their code doesn’t break in your posts!

    Exploring the Video Sites

    We’re going to work with 7 video hosting sites:

    1. YouTube (obviously!)
    2. Vimeo
    3. Dailymotion
    4. Yahoo! Screen
    5. Blip.tv
    6. Veoh
    7. Viddler

    Let’s see what their embed codes look like:

    YouTube

    The default embed code looks like this:

    /* Original video: youtube.com/watch?v=dQw4w9WgXcQ */
    
    

    But there’s one option, the “privacy-enhanced mode” which adds “-nocookie” to the domain and we’re going to use it in our shortcode.

    Vimeo

    /* Original video: vimeo.com/36804448 */
    
    

    Simple and elegant. That’s why people love Vimeo.

    Dailymotion

    /* Original video: dailymotion.com/video/xhwpbg_bridgestone-15-sec-spot_auto */
    
    BridgeStone 15 Sec spot by DailymotionUSA

    I think adding a link below the embed code is just not cool, so we’re not adding that to our shortcode.

    Yahoo! Screen

    /* Original video: screen.yahoo.com/mysterious-death-of-500-fish-in-german-lake-blamed-on-urinating-swimmers-29322943.html */
    

    The embed code is a little weird on Yahoo! Screen but I found a way to shorten it which will be easier to use in our shortcode.

    Blip.tv

    /* Original video: blip.tv/mister-glasses/episode-7-5600357 */
    
    

    This is a hard one – this doesn’t have the video ID (from the video’s URL) in the embed code. But thanks to some research, I figured out how to use the ID! :)

    Veoh

    /* Original video: veoh.com/watch/v27458670er62wkCt */
    
    Watch Intense Cat in Animals  |  View More Free Videos Online at Veoh.com

    Ah, the tag… Don’t worry, we’re not going to use it!

    Viddler

    /* Original video: viddler.com/v/978c9ba2 */
    
    

    That’s all. Now, let’s get to the fun part!


    The Shortcode: [vid]

    We’ll create 4 attributes for this shortcode – the name of the site, the ID of the video and the width and the height of the video. You can set some default values for the attributes:

    function vid_sc($atts, $content=null) 
    	extract(
    		shortcode_atts(array(
    			'site' => 'youtube',
    			'id' => '',
    			'w' => '400',
    			'h' => '250'
    		), $atts)
    	);
    
    add_shortcode('vid','vid_sc');
    

    Then comes the part where the function generates the $src variable which generates the src attribute for the iframe:

    // YouTube with "privacy-enhanced mode":
    if ( $site == "youtube" ) 
    	$src = 'http://www.youtube-nocookie.com/embed/'.$id;
    
    // Vimeo:
    else if ( $site == "vimeo" ) 
    	$src = 'http://player.vimeo.com/video/'.$id;
    
    // Dailymotion:
    else if ( $site == "dailymotion" ) 
    	$src = 'http://www.dailymotion.com/embed/video/'.$id;
    
    // Yahoo! Screen with some cuts in the URI:
    else if ( $site == "yahoo" ) 
    	$src = 'http://d.yimg.com/nl/vyc/site/player.html#vid='.$id;
    
    // Blip.tv with some "hacks" in the URI:
    else if ( $site == "bliptv" ) 
    	$src = 'http://a.blip.tv/scripts/shoggplayer.html#file=http://blip.tv/rss/flash/'.$id;
    
    // The Veoh URI has some hacks, too:
    else if ( $site == "veoh" ) 
    	$src = 'http://www.veoh.com/static/swf/veoh/SPL.swf?videoAutoPlay=0&permalinkId='.$id;
    
    // Viddler:
    else if ( $site == "viddler" ) 
    	$src = 'http://www.viddler.com/simple/'.$id;
    
    

    And of course, we return the output. Here’s the full code of our brand new video shortcode:

    function vid_sc($atts, $content=null) 
    	extract(
    		shortcode_atts(array(
    			'site' => 'youtube',
    			'id' => '',
    			'w' => '600',
    			'h' => '370'
    		), $atts)
    	);
    	if ( $site == "youtube" )  $src = 'http://www.youtube-nocookie.com/embed/'.$id; 
    	else if ( $site == "vimeo" )  $src = 'http://player.vimeo.com/video/'.$id; 
    	else if ( $site == "dailymotion" )  $src = 'http://www.dailymotion.com/embed/video/'.$id; 
    	else if ( $site == "yahoo" )  $src = 'http://d.yimg.com/nl/vyc/site/player.html#vid='.$id; 
    	else if ( $site == "bliptv" )  $src = 'http://a.blip.tv/scripts/shoggplayer.html#file=http://blip.tv/rss/flash/'.$id; 
    	else if ( $site == "veoh" )  $src = 'http://www.veoh.com/static/swf/veoh/SPL.swf?videoAutoPlay=0&permalinkId='.$id; 
    	else if ( $site == "viddler" )  $src = 'http://www.viddler.com/simple/'.$id; 
    	if ( $id != '' ) 
    		return '';
    	
    }
    add_shortcode('vid','vid_sc');
    

    Tip within the quick tip: Take note that the iframe has two CSS classes: vid and iframe-$site (e.g. iframe-youtube). You should add vid border:0; to your CSS file since we didn’t define the frameborder attribute in our iframe tag.


    Usage Examples

    The default usage is simple enough:

    [vid site="youtube" id="dQw4w9WgXcQ" w="600" h="340"]

    But to make it even simpler, we set default values for site, w and h. So, if you want to embed a YouTube video, you can just use it like this:

    [vid id="dQw4w9WgXcQ"]

    You should change the width and the height to match your blog. Also, if you use Vimeo more than YouTube, you can change the default site value to “vimeo”.

    That’s it! Add this to your functions.php file and you can start using the shortcode. Enjoy!

    Update: We’ve added a usage example section to the article now to make things clearer.

    Original from: http://wp.tutsplus.com/articles/tips-articles/quick-tip-your-own-video-shortcode/

    Writing Custom Queries in WordPress

    May 26th, 2012 Comments off

    With custom queries you can make any data reading and/or manipulation you want. Instantly a world of new possibilities open up.


    Why Use Custom Queries?

    The basic functionalities in WordPress are fine for most simple needs, but what would you do if you want to implement some specific needs? Are you writing a plugin maybe? Then you should learn how you can use SQL queries in WordPress right now! The official references can be found in the WordPress Codex (Custom Queries and the WPDB class).


    The wpdb Class

    This global WordPress class is key for using queries. In fact, every function uses this class.


    Using query

    The query function needs a string containing the custom query. The returning value is an integer corresponding to the number of rows affected/selected, and false when there is an error.

    $query = "SELECT COUNT(apple) FROM fruits";
    $wpdb->query($query);
    

    get_results

    This function gets multiple rows when executing a query. By default the result of the function is an array.

    $query = "
    	SELECT *
    	FROM wp_terms wt
    	INNER JOIN wp_term_taxonomy wtt ON wt.term_id = wtt.term_id
    	WHERE wtt.taxonomy = 'post_tag' AND wtt.count = 0";
    
    $wpdb->get_results($query);
    

    get_var

    This will return one variable from the database, but the complete result of the query is cached for later use. Returns NULL if no result is found.

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

    get_row

    A complete row will be returned as a result of the function, which can be an object, an associative array, or a numerically indexed array. NULL is the result when no matching data is found. result_type can be OBJECT, ARRAY_A or ARRAY_N (object, associative array or numbered array). Offset is an integer with a default of 0.

    $query = "
    SELECT * FROM wp_posts
    WHERE post_type = 'post'";
    
    $wpdb->get_row($query, ARRAY_A, 3);
    

    get_col

    For getting a column, use this function. Output will be a dimensional array. An empty array will be returned if no result is found. The second parameter is the column offset.

    $query = "
    SELECT * FROM wp_posts
    WHERE post_type = 'post'";
    
    $wpdb->get_col($query, 3);
    

    Prepared Queries

    According to the php.net manual:

    “They [prepared queries] can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters.”

    You can protect SQL queries against SQL injection attacks. In short data in queries must be SQL-escaped before the query is executed to prevent injection attacks. This can be easily done with the prepare method. In the following example, the values ’10′, ‘monkey’ and ‘apple’ will be escaped when used in this method.

    // Usage: $wpdb->prepare( 'query' [, value_parameter, value_parameter ... ] );
    
    $wpdb->query( $wpdb->prepare(
    	"INSERT INTO test_table (post_id, animal, food) VALUES ( %d, %s, %s )",
    	array(
    		10,
    		'monkey',
    		'apple'
    	)
    ));
    

    Setting Error Messages

    You can turn error messages on and off with the show_errors and hide_errors functions, but you can also print:

    $wpdb->show_errors();
    $wpdb->hide_errors();
    

    Cache Control

    Deleting the cache can be made with the flush function.

    $wpdb->flush();
    

    Inserting Data

    $wpdb->insert($table, $data, $format);
    
    $wpdb->insert(
    	'foods',
    	array(
    		'fruit' => 'apple',
    		'year' => 2012
    	),
    	array(
    		'%s',
    		'%d'
    	)
    );
    

    The used parameters in order are:

    • the name of the table to insert data into
    • the data to insert (column => value pairs) without escaping
    • an array of formats to be mapped to each of the values in $data. If not present, all values will be treated as strings

    Updating Data

    $wpdb->update(
    	'foods',
    	array(
    		'fruit' => 'apple',	// string
    		'year' =>  'value2'	// integer (number)
    	),
    	array( 'ID' => 1 ),
    	array(
    		'%s',	// value1
    		'%d'	// value2
    	),
    	array( '%d' )
    );
    

    The used parameters in order are:

    • table name
    • data
    • where conditions
    • format
    • where_format

    Column Information

    You can get information about the columns of the most recent result with this function. When a function has returned an OBJECT and there are properties you don’t know much about, this can be useful.

    $wpdb->get_col_info('type', offset);
    
    • Type: the information you want to retrieve, some examples are here
      • name – column name (this is the default)
      • table – name of the table the column belongs to
      • max_length – maximum length of the column
      • not_null – 1 if the column cannot be NULL
      • more can be found in the WordPress Codex WPDB reference
    • Offset: specify the column from which to retrieve information (0 is the first column)

    Referencing WordPress Tables

    WordPress database tables can be referenced in the wpdb class. This is very convenient as table names can be different than the default ones. Here’s a list of WordPress database table references:

    • $wpdb->posts;
    • $wpdb->postmeta;
    • $wpdb->comments;
    • $wpdb->commentmeta;
    • $wpdb->terms;
    • $wpdb->term_taxonomy;
    • $wpdb->term_relationships;
    • $wpdb->users;
    • $wpdb->usermeta;
    • $wpdb->links;
    • $wpdb->options;

    Note that we don’t need to include the prefix, that’s the benefit here where the wpdb class takes care of that for us.

    There we have it! A reference for custom queries in WordPress, all in one place for you.

    Original from: http://wp.tutsplus.com/tutorials/creative-coding/writing-custom-queries-in-wordpress/