Archive

Archive for June, 2012

Plugins for Monitoring Your WordPress Site’s Uptime

June 29th, 2012 Comments off

Do you know the importance of the uptime of your website? Is your site going down regularly in the middle of the night when those on the other side of the world are trying to visit? Does it take too long to respond so Google’s spiders abandon it? Let’s look at how you can monitor your website uptime.


What Is Server Uptime Monitoring?

The fact is, users and search engine spiders don’t tolerate websites which are broken. They can even punish the site’s result rating. To get notified about any error we have to use monitoring solutions. Quick tip: if you have an uptime monitoring tool, you can also use its logs to prove you’re right when discussing the service the company promised for hosting (so this can serve as very useful evidence).


“This Site Is Currently Unavailable.”

Cash

It is wise to think about a couple of questions regarding your WordPress website.

  • Is your website working continuously?
  • How much money are you losing with your webpage business due to downtime?
  • Can you measure when it does work and when it doesn’t?
  • What is the reliability or stability of your site?
  • How much traffic can it handle?
  • Do you need to reboot or reset it often?
  • Have you seen your webpage broken ever?
  • Do you get any error messages or a blank (probably white) screen?
  • Maybe empty content with default styling?

In this article we will examine three plugins which can help with this topic.


The Good Old 99% Promise

99% promise

Do you get the usual “99% promise” from your webhosting company? Some providers even go further and offer a 99.9% uptime! Of course some of them won’t do as they promised, that is why it’s important to choose a good, reliable service. Do some searching and ask some friends and experts about the chosen company. Maybe it is better to consider a more expensive package for example a VPS or dedicated hosting. Also, don’t forget about the monthly traffic, which is usually given in gigabytes. Better providers indicate this as well when offering solutions. Some things which appear cheap, actually aren’t cheap in the long run.


How Does This Thing Work?

The monitoring servers are checking your website at certain intervals (minutes, hours) and sending messages about the problems if they detected any errors. Some providers allow you to choose the interval for this operation.


Plugin: Pingdom Status

Pingdom is a big service with major users like Microsoft, Ericsson, Amazon, Vodafone and Siemens. To use this plugin you have to have a Pingdom account. This can be a free one, a 30-day-trial one, or a paid version. At Pingdom you can set multiple uptime check frequencies (1 Mins, 5 Mins, 15 Mins, 30 Mins, 60 Mins), and it has good customer service. The company has got a self-developed system for monitoring. This plugin is using the Pingdom API and makes a status page for your WordPress admin.

Pingdom settings

This tool offers:

  • alerts via multiple channels for example:
    • email
    • Twitter
    • mobile phone
  • uptime
  • response time
  • stat graphs
  • different alerts
    • up
    • down
    • repeated down
  • multiple service monitoring
    • HTTP
    • TCP
    • Ping
    • UDP

Plugin: tagBeep Uptime Monitor

Through email alerts you will know everything about the uptime of your site. You can get a yearly discount if you go for the pro or enterprise package.

tagBeep start screen

Plugin: WP Really Simple Health

This integrates to the WordPress toolbar and you can examine the following things:

  • the CPU load
  • memory usage
  • and server uptime
WP Really Simple Health admin interface status

You can set each of these (ON or OFF) at the settings screen of the plugin.

WP Really Simple Health admin interface status

Comparison of the Plugins

Pingdom tagBeep WP RSH
Last Update 2010-08-30 2012-01-24 2012-02-03
Plugin Version 1.1.4 1.1 1.0
Downloads 1,683 118 618
Min. WP Version 2.7 3.0 3.3
Compressed Size 1323 KB 31 KB 41 KB
Uses Own API Yes Yes No
Needs External Account Yes Yes No
Free Account Yes Yes N/A
Free Trial Yes Yes N/A
Email Alert Yes Yes No
Mobile Alert Yes No No
External Monitoring Servers Yes Yes No
Settings Screen Yes Yes Yes
Price Freemium Freemium Free / Donationware

Other External Providers

You can try some other companies as well, for example:


Bonus Tip

Pie chart about alerts

It is smart to turn off any error messages on your production WordPress page. You can read a very good, complete tutorial about this technique here at Wptuts+. The article even shows how to turn them into WordPress admin alerts.


Summary

Server uptime monitoring lets you quickly know about any errors. Uptime and downtime can be measured and logged. You can also prepare and improve your page using these tools.

If you already monitor your site’s uptime, what advantages has it given you? Do you know of any other tools you can recommend? Let us know in the comments below!

Original from: http://wp.tutsplus.com/tutorials/scaling-caching/plugins-for-monitoring-your-wordpress-sites-uptime/

Give Your Customers Driving Directions With the Google Maps API

June 28th, 2012 Comments off

Instead of just showing your business location on a Google Map, why not offer your users the opportunity to get driving directions on the same page? No need for them to open up a new browser window and find it themselves, we can do better than that!

Using the Google Maps API within your WordPress website is a relatively simple process and we’ll explore exactly how to do it in this tutorial.

What We’ll Be Doing in This Tutorial…

  1. First we’ll set up some custom options so that we can enter information about our map in the WordPress Admin panel.
  2. Then we’ll use shortcodes to output a map container, input fields and directions container
  3. Finally we’ll write some JavaScript to initiate the Google Map

Note: We’ll be writing a fair bit of JavaScript here, but don’t worry! This is a WordPress tutorial so feel free to gloss over the JavaScript parts :)


Step 1 Create the Directory and Files

  1. Create a folder inside your theme called Map
  2. Inside this folder, create map.php
  3. Finally create map.js

Step 2 Include the map.php File

In your functions.php file (located in the root directory of your theme) – include the map.php file you created at the top.

/* functions.php */
include('map/map.php');

Step 3 Register Settings

There are 3 things that we want to be able to edit from the Admin area.

  1. The Destination. We’re going to use Longitude and Latitude values to specify the precise location of your destination (more details to follow)
  2. The infoWindow content. This is the white bubble you often see on Google Maps – we want to be able to edit the text in the bubble!
  3. Initial Zoom Level of the map – how far the map is zoomed in when the user first loads the page.

In map.php, hook into admin_init to register our settings:

function map_init() 
	register_setting('general', 'map_config_address');
	register_setting('general', 'map_config_infobox');
	register_setting('general', 'map_config_zoom');


add_action('admin_init', 'map_init');

Now we can set up the heading text for our section in the options page and all of the inputs we need.

function map_config_option_text() 
	echo '

Set Options for the Map here:

'; // Longitude, Latitude Values for the Destination function map_config_address() printf((''), get_option('map_config_address')); // The text content for the InfoWindow Bubble function map_config_infobox() printf((''), get_option('map_config_infobox')); // The initial Zoom Level of the map. function map_config_zoom() printf((''), get_option('map_config_zoom'));

Finally we hook into admin_menu to display our settings in the WordPress Admin:

function map_config_menu() 
	add_settings_section('map_config', 'Map Configuration', 'map_config_option_text', 'general');
	add_settings_field('map_config_address', 'Address - Longitude and Latitude', 'map_config_address', 'general', 'map_config');
	add_settings_field('map_config_infobox', 'Map InfoWindow', 'map_config_infobox', 'general', 'map_config');
	add_settings_field('map_config_zoom', 'Map Zoom Level', 'map_config_zoom', 'general', 'map_config');

add_action('admin_menu', 'map_config_menu');

Go into your admin area, you should now see this:


Step 4 Enter Your Destination, infoWindow Text and Zoom Level

  1. Destination Address

    The Google Maps API actually accepts regular addresses such as ‘Newgate Lane, Mansfield, Nottinghamshire, UK’ – However, you’ll find that you will want to be more precise with your destination (for example, you’ll most likely want to point directly to your business and not just the street). You can use a Google Maps API V3 Sample to search for your destination. Drag the target around until you have pin-pointed your spot. When you’re happy, copy the Lat/Lng: value into the address field in the options – for example 27.52774434830308, 42.18752500000007 (just the numbers separated by the comma, no brackets or quotes!)

  2. InfoWindow Text

    Make this whatever you want. Your Business Name would be a good idea :)

  3. Zoom Level

    A good starting point is 10.

Click ‘Save Changes’ and when the page refreshes you can check that the info has been stored. It should look something like this now:


Step 5 Set Up the Shortcodes

When we are finished, we’ll have 3 elements: the Map, the Form, and the Directions – so in this tutorial I’ve decided to split them up into 3 separate shortcodes. This will allow us to change the order/placement of each item without having to modify any of our PHP code. For example, you may decide to have your directions above the map instead of below, or at the side, etc.

  1. Shortcode 1 : wpmap_map

    Here we register and enqueue the Google Maps API JavasScript file as well as our own maps.js file.

    Next we use the $output variable to store our map-container div along with some custom data attributes. ( data-map-infowindow will store the content for the infowindow and data-map-zoom will represent the initial zoom level – both of these values are returned using WordPress’s get_option function).

    Finally we return the generated HTML to be output:

    		function wpmap_map() 
    
    			wp_register_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false');
    			wp_enqueue_script('google-maps');
    
    			wp_register_script('wptuts-custom', get_template_directory_uri() . '/map/map.js', '', '', true);
    			wp_enqueue_script('wptuts-custom');
    
    			$output = sprintf(
    				'
    ', get_option('map_config_infobox'), get_option('map_config_zoom') ); return $output; add_shortcode('wpmap_map', 'wpmap_map');
  2. Shortcode 2 : wpmap_directions_container

    Here we simply return an empty div with an ID of dir-container. This will act as the container for the directions.

    		function wpmap_directions() 
    
    			$output = '
    '; return $output; add_shortcode('wpmap_directions_container', 'wpmap_directions');
  3. Shortcode 3 : wpmap_directions_input

    This generates the Markup needed for our form.

    This is also where we’ll set our final custom option – the destination Address. This time, we’ll use a hidden form field to hold the Latitude/Longitude value that we entered earlier in the Admin Panel.

    		function wpmap_directions_input() 
    
    			$address_to = get_option('map_config_address');
    
    			$output = '
    For Driving Directions, Enter your Address below :
    '; return $output; add_shortcode('wpmap_directions_input', 'wpmap_directions_input');

Now we have the shortcodes set up, you can go ahead and type them into your Contact Us page (or any page you like).

If you preview the page now, all you’ll see is the form input fields. That’s because we haven’t written our JavaScript that will initialize the Map yet and the div for the directions is currently empty.

Note: Before we dive into the JavaScript, we just need to add this to our style.css:

#map-container 
	width: 100%;
	height: 400px;


Step 7 Writing JavaScript to Interact With Google Maps API

Now it’s time to make the magic happen! I’ll provide a quick run-down of what we’re going to do first, then we’ll dig straight into the code.

  1. First we’re going to create an object WMmap and assign properties to it (some of which we’ll be grabbing from the markup that we created in the shortcodes)
  2. Then we’ll add a few methods to handle the functionality of the map and directions.
  3. One of these methods, init, will be responsible for loading the map and also for setting some default values such as the infoWindow text, zoom level and initial marker position (all from WordPress options)
  4. Finally we’ll set an event listener to load our map when the page is ready.

Ready?

I’ll explain each part of the code step-by-step, but don’t worry if you get lost, we’ll put it all together at the end.

Set Properties

Let’s create our object and set some properties. Here we are simply querying the DOM to retrieve the HTML elements that contain the values we need. The property names we’re using should be very clear and self-explanatory (mapContainer is obviously the Map Container, etc :) )

Here we also get a couple of objects from the API that we’ll use later when we deal with Directions.

var WPmap = 

	// HTML Elements we'll use later!
	mapContainer	: document.getElementById('map-container'),
	dirContainer	: document.getElementById('dir-container'),
	toInput			: document.getElementById('map-config-address'),
	fromInput		: document.getElementById('from-input'),
	unitInput		: document.getElementById('unit-input'),

	// Google Maps API Objects
	dirService		: new google.maps.DirectionsService(),
	dirRenderer		: new google.maps.DirectionsRenderer(),
	map				: null,

	/* continues below */

The Methods

These are also part of our WPmap object, if you are unsure how everything ties together, be sure to check out the bottom of this tutorial to see all of the code together.

showDirections()

This is called from within another method that we’ll see later, it basically controls the insertion of the directions into the page.

/* within WPmap object */
showDirections:function (dirResult, dirStatus) 
	if (dirStatus != google.maps.DirectionsStatus.OK) 
		alert('Directions failed: ' + dirStatus);
		return;
	

	// Show directions
	WPmap.dirRenderer.setMap(WPmap.map);
	WPmap.dirRenderer.setPanel(WPmap.dirContainer);
	WPmap.dirRenderer.setDirections(dirResult);
},

getStartLatLng()

This is called once from our init method. It will set the startLatLng property equal to a google.maps.LatLng object that we can use later. It requires that we provide it separate Latitude and Longitude values – how can we do this?

  1. In our shortcode we inserted a hidden form field that contains the Latitude & Longitude value that we set in the WordPress Admin. Then we retrieved the hidden form field and stored it in toInput. This means we can now access the value using WPmap.toInput.value
  2. However, the value we set in the form is just a string with a comma separating the numbers. To separate the values we can split the string up using .split(","). This will return an array containing the Latitude and Longitude as separate values.
  3. Now we can access each one by using the arrays index.
	/* within WPmap object */
	getStartLatLng: function () 
		var n = WPmap.toInput.value.split(",");
		WPmap.startLatLng = new google.maps.LatLng(n[0], n[1]);
	,

getSelectedUnitSystem()

Because we have allowed our users to select whether they would prefer directions in Metric or Imperial, we use this method to set DirectionsUnitSystem to either METRIC or IMPERIAL.

	/* within WPmap object */
	getSelectedUnitSystem:function () 
		return WPmap.unitInput.options[WPmap.unitInput.selectedIndex].value == 'metric' ?
			google.maps.DirectionsUnitSystem.METRIC :
			google.maps.DirectionsUnitSystem.IMPERIAL;
	,

getDirections()

This is the method that is called when the user clicks the Get Directions button.

  1. First we get the address that the user entered and store it in the fromStr variable.
  2. Next we set up an options object – dirRequest. This will contain the options needed to provide the Driving Directions.
    1. origin – The address that the user entered.
    2. destination – The google.maps.LatLng object containing the Latitude and Longitude values of your destination.
    3. travelMode – Here we ensure we are only retrieving Driving Directions.
    4. unitSystem – Specify which unit of measurement to use based on user’s choice.
  3. Finally, we call WPmap.dirService.route – and pass two parameters to it:
    1. dirRequest – this is the object containing our options.
    2. WPmap.showDirections – the callback function that handles the placement of the directions into the page.
	/* within WPmap object */
	getDirections:function () 

		var fromStr = WPmap.fromInput.value;

		var dirRequest = 
			origin      : fromStr,
			destination : WPmap.startLatLng,
			travelMode  : google.maps.DirectionsTravelMode.DRIVING,
			unitSystem  : WPmap.getSelectedUnitSystem()
		;

		WPmap.dirService.route(dirRequest, WPmap.showDirections);
	},

init()

This is the method that is called when the page is loaded. It is responsible for :

  1. Initiating the map, centered on your address.
  2. Retrieving values that are needed to set the infoWindow text and the initial Zoom level.
  3. Setting a marker pin showing your address.
  4. Listening for when when a user clicks ‘Get Directions’ so that it can remove the initial Marker and infoWindow
	init:function () 

		// get the infowindow text and zoom level
		var infoWindowContent = WPmap.mapContainer.getAttribute('data-map-infowindow');
		var initialZoom       = WPmap.mapContainer.getAttribute('data-map-zoom');

		// call the method that sets WPmap.startLatLng
		WPmap.getStartLatLng();

		// setup the map.
		WPmap.map = new google.maps.Map(WPmap.mapContainer, 
			zoom      : parseInt(initialZoom),
			center    : WPmap.startLatLng,
			mapTypeId : google.maps.MapTypeId.ROADMAP
		);

		// setup the red marker pin
		marker = new google.maps.Marker(
			map       : WPmap.map,
			position  : WPmap.startLatLng,
			draggable : false
		);

		// set the infowindow content
		infoWindow = new google.maps.InfoWindow(
			content : infoWindowContent
		);
		infoWindow.open(WPmap.map, marker);

		// listen for when Directions are requested
		google.maps.event.addListener(WPmap.dirRenderer, 'directions_changed', function () 

			infoWindow.close();         //close the initial infoWindow
			marker.setVisible(false);   //remove the initial marker

		);
	}//init

};// <-- this is the end of the object.

** Optional **

If you want to display a nice message (like the one seen below) to your users after they have requested directions, just copy the code under the image into the event listener inside the init method.

Optional Thank you message:

	// Get the distance of the journey
	var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;

	// set the content of the infoWindow before we open it again.
	infoWindow.setContent('Thanks!
Looks like you're about ' + distanceString + ' away from us.
Directions are just below the map'); // re-open the infoWindow infoWindow.open(WPmap.map, marker); setTimeout(function () infoWindow.close() , 8000); //close it after 8 seconds.

Step 8 Add the Event Listener That Will Load the Map

Are you still with me? We’ve made it all the way to end now and all that’s left to do is call the WPmap.init() method when the page loads. Add this to the bottom of map.js

google.maps.event.addDomListener(window, 'load', WPmap.init);

Putting All the JavaScript Together

We’ve covered a lot of ground here, so let’s see how it looks when it’s all put together.

var WPmap = 

	// HTML Elements we'll use later!
	mapContainer   : document.getElementById('map-container'),
	dirContainer   : document.getElementById('dir-container'),
	toInput        : document.getElementById('map-config-address'),
	fromInput      : document.getElementById('from-input'),
	unitInput      : document.getElementById('unit-input'),
	startLatLng    : null,

	// Google Maps API Objects
	dirService     : new google.maps.DirectionsService(),
	dirRenderer    : new google.maps.DirectionsRenderer(),
	map:null,

	showDirections:function (dirResult, dirStatus) 
		if (dirStatus != google.maps.DirectionsStatus.OK) 
			alert('Directions failed: ' + dirStatus);
			return;
		

		// Show directions
		WPmap.dirRenderer.setMap(WPmap.map);
		WPmap.dirRenderer.setPanel(WPmap.dirContainer);
		WPmap.dirRenderer.setDirections(dirResult);
	},

	getStartLatLng:function () 
		var n = WPmap.toInput.value.split(",");
		WPmap.startLatLng = new google.maps.LatLng(n[0], n[1]);
	,

	getSelectedUnitSystem:function () 
		return WPmap.unitInput.options[WPmap.unitInput.selectedIndex].value == 'metric' ?
			google.maps.DirectionsUnitSystem.METRIC :
			google.maps.DirectionsUnitSystem.IMPERIAL;
	,

	getDirections:function () 

		var fromStr = WPmap.fromInput.value; //Get the postcode that was entered

		var dirRequest = 
			origin      : fromStr,
			destination : WPmap.startLatLng,
			travelMode  : google.maps.DirectionsTravelMode.DRIVING,
			unitSystem  : WPmap.getSelectedUnitSystem()
		;

		WPmap.dirService.route(dirRequest, WPmap.showDirections);
	},

	init:function () 

		// get the content
		var infoWindowContent = WPmap.mapContainer.getAttribute('data-map-infowindow');
		var initialZoom       = WPmap.mapContainer.getAttribute('data-map-zoom');

		WPmap.getStartLatLng();

		// setup the map.
		WPmap.map = new google.maps.Map(
			WPmap.mapContainer,
			
				zoom: parseInt(initialZoom),     //ensure it comes through as an Integer
				center: WPmap.startLatLng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			
		);

		// setup the red pin marker
		marker = new google.maps.Marker(
			map: WPmap.map,
			position: WPmap.startLatLng,
			draggable: false
		);

		// set the infowindow content
		infoWindow = new google.maps.InfoWindow(
			content:infoWindowContent
		);
		infoWindow.open(WPmap.map, marker);

		// listen for when Directions are requested
		google.maps.event.addListener(
			WPmap.dirRenderer,
			'directions_changed',
			function () 

				infoWindow.close();         //close the first infoWindow
				marker.setVisible(false);   //remove the first marker

				// setup strings to be used.
				var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;

				// set the content of the infoWindow before we open it again.
				infoWindow.setContent('Thanks!
Looks like you're about ' + distanceString + ' away from us.
Directions are just below the map'); // re-open the infoWindow infoWindow.open(WPmap.map, marker); setTimeout(function () infoWindow.close() , 8000); //close it after 8 seconds. } ); }//init }; google.maps.event.addDomListener(window, 'load', WPmap.init);

Tutorial Notes

  1. Be sure to research anything you don’t understand on Google’s Maps API Website
  2. When writing this tutorial, I was testing my code using the stock TwentyEleven WordPress Theme. Something was causing the arrow at the bottom of the InfoWindow on the map to display incorrectly. It’s because .entry-content img on line 857 has a max-width set. This screws up the way that Google renders the infoWindow. To fix it, enter this somewhere below it:

    			#map-container img  max-width: none; 
    		

Original from: http://wp.tutsplus.com/tutorials/creative-coding/give-your-customers-driving-directions-with-the-google-maps-api/

Website Navigation Trends for Various Layouts

June 28th, 2012 Comments off

There are always some key aspects in designing a website which you have to give full attention. Site navigation is one of these important features which is found in every single layout design. Nav links generally lead to the most important pages in your website and help visitors get around quicker. You’ll often find these above-the-fold where the page cuts off at the bottom of your web browser.

Considering some design ideologies we can determine powerful trends in building navigation menus. These roll over into many other realms of design including mobile and tablet PC. You have to think of navigation links as your visitor’s main control panel over the website. This is how people will maneuver through each of your pages and come to eventually find what they need.

Static Nav Bars

You can build a professional design style using a fixed navigation bar in your website. This is often positioned just underneath the logo or directly at the top of your layout. I can reference a great example from the Fork CMS webpage.

Default top navigation links - Fork CMS

In this scenario Fork has actually placed their logo inline with the other links. Often you need a very wide layout style which allows for the top bar to span all the way across. You could alternatively limit the width based on a content wrapper and this will produce the same effect.

What I like about this style is the direct understanding that it just works. Users know to scroll towards the top and they will find all the major links required. You can even download the latest version of their CMS from the Download link to the far right. Take notice this is actually colored a bright yellow to stand out from the other typical page links.

Oversized Headers

The header area of your webpage layout is generally the first place visitors look for navigation links. When you’ve got super oversized fonts or icons these tend to draw even more attention. If you have the skills to design custom textures or graphics you can use these within a typical nav menu.

Take the example of Sarah Longnecker’s portfolio where she has the most important links floating towards the top right. Depending on which page you’re currently viewing the specified link will have a selected state with a background ribbon. This is a perfect example of how you can offer at-a-glance information to the user without taking up much room.

Sarah Longnecker video portfolio works

If you also notice Sarah has placed links in the sidebar and footer area of her layout. This isn’t to say these links aren’t as important. But when people visit her website they will mostly be interested in the main core pages. If you have time to spend browsing around you may enjoy some of her other blog posts, yet these are not fundamental to the website itself.

Vertical Parallax Scrolling

I have seen this trend become adopted much faster among web design firms and smaller portfolios. You can code a super long webpage in one file with all of your content together while the navigation links slide your position up and down the page. This is a similar style to parallax web design except we’re limited to the up/down directions.

parallax scrolling navigation contact form - Snoggle Media

The Snoggle Media website has a fixed navigation setup on the left side. As you scroll down the page it acts as a sticky of which you always have immediate access. What’s interesting is that each of the pages can actually be viewed individually. However from the homepage you also have access to each important section like the blog, portfolio projects, and contact form without leaving the root URL.

Whiteboard portfolio site design - parallax navigation

Whiteboard is another such example where you can begin scrolling down the page and a whole new navigation menu appears up top. As you click between these links the page will scroll around in a similar parallax fashion.

Their design also offers individual pages for most of the core sections. This is nice so that you can have a working permalink to share with others if needed. But their design is also very crowded – it works for some people however I find it difficult to digest all the information. Be careful with these types of fixed navigation links so that you aren’t alienating users who may be on older web browsers or smaller monitor screens.

Content-Heavy Dropdowns

We are all familiar with dropdown navigations which have a main top link along with additional sub-links. I have noticed a trend for larger blogs and magazines that have very detailed dropdown menus. These often include links to recent posts and other top category archives.

Mashable magazine 2012 dropdown navigation links

I can immediately consider the new Mashable navigation where you can hover over each of the top categories to reveal a whole lot more information. This dynamic dropdown window includes the latest posts from that category, along with other sub-categories you can choose. But this isn’t even the end of their dynamic efforts.

As you hover over each of the sub-links the story content will automatically refresh using Ajax. So as you hover over the different links inside Tech(Apps, Gadgets, Mobile) you’ll be given the latest stories published in each of these smaller categories. This is a brilliant idea from the user’s perspective as there is much less clicking around to navigate between pages.

Design Links into the Layout

This is a trend much harder to spot than anything else. What you want to do is design your layout around the purpose of having tons of links between all your archives and main content. The newest Smashing Magazine design features website resources at the top with high-traffic categories in the left sidebar.

Header navigation links for Smashing Magazine

As you scroll down you’ll find more links in the right sidebar along with block lists inside the footer section. When you run a popular blog such as Smashing Mag you end up trying out new and distinct layout ideas. It just feels natural to find all of these internal content links scattered in different places. And the best part is they don’t feel awkward in the website – their layout almost seems to wrap around the links in a very comfortable position.

popular footer links for Smashing Magazine design writing

If you have a solid idea like this navigation system keep practicing until you’re satisfied. You probably won’t feel great with the first iteration, but as you try out new strategies you’ll be learning in the process. Designing powerful navigation menus is all about learning from your past mistakes and not being afraid to jump into unknown territory!

Final Thoughts

These are just some of the more popular design trends found in 2012. For as long as we have the Internet there will always be a need for websites, and these sites must have some form of navigation. The methods of building links will certainly change as newer standards are adopted.

However the functionality of these navigation systems will remain fixed. Users are very comfortable with the current system and it’s almost like a 6th sense picking up on how to move through different pages. If you have similar examples of unique navigation trends definitely share with us in the post comments area below.

You might also like…

40 Recently Released jQuery Plugins →
25 jQuery Plugins to help with Responsive Layouts →
20 jQuery Image and Multimedia Gallery Plugins →
50 jQuery Plugins for Form Functionality, Validation, Security and Customisation →
15 CSS3 Navigation and Menu Tutorials and Techniques →
20 CSS3 Tutorials and Techniques for Creating Buttons →
24 CSS (in some cases with jQuery) Navigation and Menu Tutorials →
22 CSS Button Styling Tutorials and Techniques →
50 Fundamental jQuery Controls, Components and Plugins →



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

Categories: Web development Tags:

Beautiful Candid Photography – An expression of what it is to be human

June 27th, 2012 Comments off

We are social beings, but often find ourselves isolated. While it’s in our nature to gather together, getting close to anyone takes effort and skill. No where is this more true than in the world of photography. A candid picture that really captures what an honest moment is like can be shockingly hard to take.

All the same, we have found 30 images that do exactly that. They take a moment from the life of a living breathing human, and save to it be experienced by others. An expression of what it is to be a human being.

Photography Comes First…

Photography Comes First... - Candid Photography

Candid

Candid - Candid Photography

Tenderness

Tenderness - Candid Photography

Catch the Wind

Catch the Wind - Candid Photography

Candid Photograph

Candid Photograph - Candid Photography

A Face in the Crowd

A Face in the Crowd - Candid Photography

Danny Photography

Danny Photography - Candid Photography

Lady and Bike

Lady and Bike - Candid Photography

A Gentleman of the Road

A Gentleman of the Road - Candid Photography

Candid Photograph by Chiril

Candid Photograph by Chiril - Candid Photography

Dannys Candid Photography

Dannys Candid Photography - Candid Photography

Shake your Booty!

Shake your Booty! - Candid Photography

Play

Play - Candid Photography

Angelic Dance

Angelic Dance - Candid Photography

Day Seventy Seven

Day Seventy Seven - Candid Photography

Its all about the Baby

Its all about the Baby - Candid Photography

Fine Feathered Friend

Fine Feathered Friend - Candid Photography

All is not as it seems

All is not as it seems - Candid Photography

A Tale of Two Cities

A Tale of Two Cities - Candid Photography

Candid Street Photography

Candid Street Photography - Candid Photography

Women On the Move & Carefree

Women On the Move & Carefree - Candid Photography

This way!

This way! - Candid Photography

The Soloist

Life - Candid Photography

Smoke

The Soloist - Candid Photography

Future Discussion

Future Discussion - Candid Photography

Spiner Spinster

Spiner Spinster - Candid Photography

Jogging With My Iguana And Hat On

Jogging With My Iguana And Hat On - Candid Photography

Cheesee

Cheesee - Candid Photography

Bad Weather

Bad Weather - Candid Photography

Life on the Road

Life on the Road - Candid Photography

Love will keep us Alive

Love will keep us Alive - Candid Photography

City Strollers

City Strollers - Candid Photography

Choosing a Candid Wedding Photographer

Choosing a Candid Wedding Photographer - Candid Photography

Hot Town, Bubbles in the City

Hot Town, Bubbles in the City - Candid Photography

Smiling Eye

Smiling Eye - Candid Photography

You might also like…

Inspirational and Free Downloadable Photography Magazines →
Beautiful Examples of Photoshopped Smoke Art and Technique Tutorials →
Amazing Images That Could Be HDR – But are definitely Not →
Tutorials for Creating Beautiful HDR (High Dynamic Range) Imagery →
Amazing Examples of Conformal Photography. How do they do this? →
50 Beautiful HDR Images from 50 World Cities →
Beautiful Examples of Photoshopped Smoke Art and Technique Tutorials →
Creative Photography Examples using the Polar Panorama Effect →
Creative and Inspirational Photographs – Distil Ennui →
Examples of Stylish Sabatier (or Solarised) Effect Photography →
Amazing Examples of Conformal Photography. How do they do this? →



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

Quick Tip: Saving a Default Post Thumbnail

June 27th, 2012 Comments off

This tutorial will demonstrate how to create a Default Post Thumbnail from the core. Many tutorials demonstrate how to check if a thumbnail exists in a post and then render one if no thumbnail exists. This tutorial will show you how to avoid saving a post without a thumbnail, in the first place.


Usual Way to Get Default Thumbnail

As mentioned before, some tutorials suggest making an If ... Else statement in the theme to show a default thumbnail. An example is as follows:

if (has_post_thumbnail()) 
	the_post_thumbnail();

else 
	echo 'thumbnail';

That simple statement will work, but it would require modifying third-party plugins that do not have default thumbnail features. Which is why, this tutorial will save a default thumbnail to the database.


Step 1 Getting the Thumbnail ID

The first thing you have to do is fetch the ID of the uploaded thumbnail you will be using. You do this by visiting the Media Library, selecting your image, and collecting the ID.

In the screenshot, one collects the ID integer from the address bar where “attachment_id=“.


Step 2 Coding the Function

To add the default thumbnail feature, you can add the following snippet to your functions.php file in your theme folder.

add_action( 'save_post', 'wptuts_save_thumbnail' );

function wptuts_save_thumbnail( $post_id ) 

	// Get Thumbnail
	$post_thumbnail = get_post_meta( $post_id, $key = '_thumbnail_id', $single = true );

	// Verify that post is not a revision
	if ( !wp_is_post_revision( $post_id ) ) 
		// Check if Thumbnail exists
		if ( empty( $post_thumbnail ) ) 
			// Add thumbnail to post
			update_post_meta( $post_id, $meta_key = '_thumbnail_id', $meta_value = '233' );
		
	}

}

We use the save_post hook to trigger our function and get the recently added post. Once we are referencing the recently added post, we use get_post_meta to get the value from the database for thumbnail ID where the post ID is the last inserted. Next we use the wp_is_post_revision function to check whether the saved post is a revision or a new post. If the post is a revision, then we will void the rest of the function. Using an If statement, we check to see if any meta data for the thumbnail exists. If none exists, then we use the add_post_meta function to add the default thumbnail’s ID to the last inserted post.

Voila! During a save on draft save, the default thumbnail will be saved to the database and is now available for use in Widgets or Plugins that use thumbnails. If you are building a theme, you can use this method and replace the $meta_value with an image from your theme file. Happy Coding!

Original from: http://wp.tutsplus.com/articles/tips-articles/quick-tip-saving-a-default-post-thumbnail/

Useful Tips To Get New Web Design Clients

June 26th, 2012 Comments off

Many freelancers begin their careers without a formal marketing plan for their web design business. The truth is that sales and marketing is a crucial part of all businesses, and that is why your clients hire you. Today’s business owners know a great website is an important part of their marketing toolkit, and since this is your career you should have an awesome website yourself. While a great site is critical for a web designer, don’t depend on it as your only marketing tool.

Image Source: Web Designer Tools via Shutterstock

Whether you are a novice designer or already have a good book of existing clients, gaining new clients is vital to the ongoing success of your business. Use these offline and online tips and tricks to find clients in unusual ways and keep your freelance web design business growing.

Offline Marketing for Web Designers

Disclaimer: Yes, these methods require some old-fashioned face-to-face communication. However, they are effective, especially when coupled with some new-fangled technology tricks.

Make a list of your centres of influences

“My whats?” you say. Centres of influences are people you know whose standing or success in the community can influence the decisions of others. They are often asked for recommendations to other professionals. For example, doctors, dentists, real estate agents, accountants and lawyers. The next time you see one of these fine folks, give them a business card and let them know you can help them set up a new website or spruce up the one they already have. Centres of influence can be a wonderful source of referrals to others who need your services.

Target businesses in industrial parks

Drive to an industrial park and actually check out the businesses or stores. New businesses and those undergoing renovations make great web design clients because they are enthusiastic about their new ventures and want to promote them. Older, more established businesses may not even have a website, especially if they started before the internet! Make a list of five to ten businesses and contact them by email, phone or in person to offer your services.

Join your area business networking organizations, business improvement associations and/or chamber of commerce

Join a breakfast club where other small business owners discuss the joys and difficulties of running a business. Mingle. Make small talk. (Don’t shudder.) Offer to look at websites, and if you have time, use your mobile device to take a quick look right there. Give one or two suggestions and your card.

Research regional available resources catering to small businesses

Look for classes, workshops or seminars for new businesspeople. Inquire about speaking to a class about setting up a website for new businesses. Better yet, offer to design a website for the resource itself. If they are happy with your work they are more likely to promote your web design services to the students. Also look for programs offering municipal or federal funding to new businesses. Small business owners who have just received a grant from the government have money to spend on marketing, including a professionally designed site.

Image Source: 3d Small People via Shutterstock

Local restaurants or coffee shops

Seriously. Target establishments in business districts. Begin by looking at the website for the restaurant itself, and get in touch with the owner to offer your services to update or design the restaurant website. Ask to put up a poster, brochure, or leave paper coasters with your logo or QR code on them. If you really want to make an impression as a cutting-edge web designer, place a digital advertisement on the restroom mirrors to get people talking and attract new clients who want innovation and creativity.

Contractors, plumbers, electricians and other tradesmen are good sources of new web design business

As more people turn to the internet to find local tradespeople, these professionals need websites. Leave marketing material in building supply stores, lumber yards, plumbing supply outlets, and any other places you think they will hang out – even your neighbourhood pub.

Go old-school and print a stack of notices or posters about your business

Include a QR code leading to your website or a coupon for a discount on your web design services . Post these notices on the bulletin board at your local post office and business supply stores, where all the local entrepreneurs end up sooner or later.

Libraries often offer free talks to their patrons on a wide variety of subjects

Contact the information desk at your local library and offer a half hour presentation on websites for businesses. This is your chance to speak loudly in the library without getting kicked out.

Pre-emptive referrals

When a client mentions a problem – for example a leaky faucet in the lunchroom, suggest the name of an area plumber you like and trust. Write the name and phone number on the back of your own business card. You are more likely to get a referral back or even get work from the plumber himself.

Ongoing and Online Marketing for Web Designers

Not all of us are fantastically proactive and outgoing marketers in the real world. In that case, be proactive online, especially if you prefer to avoid or limit your offline marketing techniques.

Introduce your business to online organizations whose members belong to specific professions

For example, engineers, doctors, lawyers or veterinarians belong to professional national or regional organizations which grant them their licenses or designations to practice. They pay fees to these organizations which often have websites, a newsletters, and blogs for their online readers. Write a guest post for the organization blog aimed at the membership – something along the lines of “5 Things to Remember When Designing Your Veterinarian Website.” Many entrepreneurs say “I’ll do my own website, thank you very much,” not realizing the work involved and expertise required. Soon they discover they are too busy designing bridges or neutering cats to worry about getting their websites up and running. They will read the post, think “yikes, I have to remember all that?” and decide they need a professional website designer.

Send warm emails to businesses you regularly visit

Personalize the email so it stands out, and begin by pointing out a product or service you love. For example, “ I just wanted to tell you that your new butter pecan lattes are fantastic.” Mention you looked them up online to find something – (hours, other locations, whatever) and offer a tip or two to improve their site. I noticed x y z – I can make it better. If you change a and b you will increase your traffic. I can help you with this. Let me know. Be nice, and don’t tell them their website is awful, even if it is. Instead, focus on what you can do to help them improve the site. Keep your email short and friendly.

Ask for referral as part of your email signature

“We value your business. The greatest compliment you can give ABC Design is to tell your friends, family and business colleagues about the services we offer. Thank you for trusting us with your web design needs!

Write a guest blog piece for a website targeting specific groups

You are probably sick of being told to write guest blogs, but you know what? It works, and it works better to specialize in a specific niche and market yourself as an expert in designing plumbing sites, or recipe sites, or landscaping sites. Even better, target a specific professional niche of individuals that are likely too busy to nickel and dime you over your fees, such as architects, engineers, doctors, lawyers, dentists, investment professionals, and real estate agents.

Image Source: Blog Plan Puzzle via Shutterstock

Become an online authority

People want to deal with an expert. Build your reputation as an expert online and offline. Become active in forums and discussions around marketing and small business and entrepreneur issues. Open a Quora account and answer questions on web design issues.

Write in your local newspaper

Okay, this may be offline, but it requires minimal face to face interaction. Provide a free weekly or biweekly column. It establishes you as a local web design business, and as a reliable professional.

READ your local paper (online or offline) for announcements about new businesses or other places that may need a website revamp.

Join LinkedIn business groups for B2B sales leads

They can be location-based or represent a niche or demographic you would like to specialize in. Join in conversations, provide thoughtful and insightful information as well as links to websites you have created (or your own website) when suitable.

Connect with other technology-related businesses

Web hosting providers, IT support businesses, graphic artists and content writing professionals all serve customers who are likely to need web design services. It is well worth developing a relationship with professionals in these fields as they can be an excellent source of referrals to new clients, as well as provide opportunity for you to branch out into other areas if you want to spread your wings beyond a career as a freelance web designer.

Provide great service to existing customers to gain their future business

How many of your clients are serial entrepreneurs, the kind of people who always have a new idea? More businesses mean more websites. Do an awesome job on the first one and you’ll have more work to come. Ask clients what they are working on, and tell them about new techniques, technology or other tips that could suite their new projects – Mobility First, anyone?

Ask for referrals from existing customers

at the end of every meeting or interaction. Provide incentives for referrals that result in new clients, such as a discount on a future site upgrade.

These are just a few techniques used by successful freelancers to find new clients and new work. Use them to inspire your marketing and networking techniques. If you have a really fantastic story of what works for you, please feel free to share it in the comments section!

You may also like…

Good Old Static HTML Sites Aren’t Dead Yet. Should They Be? →
Should You Keep Your Website Open Source? →
Should Designers know how to code? What do you think? →
Is a Design House-Style Really Necessary? →
Ode To a Wooden Spoon – How The Right Tool Can Help You Design Better →
10 Things Designers Can Learn From Pastry Chefs →
Apple Pie Appeal: How Simple, Classic Design Works →
Repeat Work and the Search For The Holy Grail →
Thoughts and Considerations for Freelancing on a Part-Time Basis →
Is Working Freelance Really Worth It? Pros and Cons →
Tips for Converting Your Freelance Operation into a Business →
Thoughts on why Spec Work is Bad and Why You Shouldn’t Do It →
Technostress – The Freelancers Disease? →



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

Categories: Web development Tags:

We have 5 Tokokoo bundles (13 WordPress themes) to giveaway – Comment to enter

June 26th, 2012 Comments off

This weeks giveaway comes from Tokokoo. Five lucky readers will win a bundle of 13 premium e-commerce WordPress Themes (with a Standard Theme license) all courtesy of the guys from Tokokoo. Scroll down to see what themes are included in the bundle.

All you will have to do for a chance of winning one of these bundles is leave a comment below telling us which is your favorite theme from the bundle.
This competition will run for the next 7 days (ending on the 3rd of July 2012) with all winners chosen at random.

tokokoo wordpress ecommerce themes

About Tokokoo

Founded in 2010 and based in Indonesia, Tokokoo.com are an e-commerce themes provider, focused on WordPress that currently offers 20 premium themes and with many more currently in development.

tokokoo wordpress ecommerce themes

Here are the 13 Premium WPEC Themes each winner will win, click for more information about each:

  1. Dapur Kue
  2. Paloogada
  3. Fabulous
  4. TokoBuku
  5. OlahRaga
  6. Bookoo
  7. Parquet
  8. Kakileema
  9. Bangkoo
  10. Disco
  11. Dangdoot
  12. Kelontong

How to Enter

For a chance of winning one of these memeberships all you have to do is leave a comment below telling us which is your favorite theme from the bundle.
This competition will run for the next 7 days (ending on the 3rd of July 2012) with all winners will be chosen at random.

Good luck guys! :-)



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

Capabilities and Nonces

June 26th, 2012 Comments off

In this previous article I looked at helping keep your theme or plug-in secure through appropriate data sanitization and validation. In this article, we’ll be looking at another important aspect of WordPress security: capabilities and nonces.

When developing a plug-in (and to a lesser extent, themes) you will often find that you want to allow a user to perform various actions: delete, edit or update posts, categories, options or even other users. More often than not you only want certain authorised users to perform these actions. For this, WordPress uses two concepts: roles and capabilities.


Front-End Delete Link: A Simple Example

Let’s suppose we want a front-end delete button to quickly remove posts. The following creates a link wherever we use wptuts_frontend_delete_link() inside the loop.

function wptuts_frontend_delete_link() 
	$url = add_query_arg(
		array(
			'action'=>'wptuts_frontend_delete',
			'post'=>get_the_ID();
		)
	);

	echo  "Delete";
}

Then to process the delete action:

if ( isset($_REQUEST['action']) && $_REQUEST['action']=='wptuts_frontend_delete' ) 
	add_action('init','wptuts_frontend_delete_post');


function wptuts_frontend_delete_post() 

	// Get the ID of the post.
	$post_id = (isset($_REQUEST['post']) ?  (int) $_REQUEST['post'] : 0);

	// No post? Oh well..
	if ( empty($post_id) )
		return;

	// Delete post
	wp_trash_post( $post_id );

	// Redirect to admin page
	$redirect = admin_url('edit.php');
	wp_redirect( $redirect );
	exit;

Then when a user clicks the ‘delete’ link, the post is trashed and the user is redirected to the post admin screen.

The problem with the above code is that it performs no permission checks: anyone can visit the link and delete a post – not only that, but by changing the post query variable they can delete any post. First of all, we want to make sure that only people who we want to be able to delete posts are able to delete posts.


Permissions, Roles and Capabilities

When a user is registered on your WordPress site they are assigned a role: this might be admin, editor or subscriber. Each role is assigned capabilities, for example edit_posts, edit_others_posts, delete_posts or manage_options. Whichever role a user is assigned, they inherit those capabilities: capabilities are assigned to roles, not users.

These capabilities dictate which parts of the admin screen they can access, and what they can and cannot do while there. It’s important to note that when checking permissions you check the capability, and not the role. Capabilities can be added or removed to roles, and so you cannot assume that an ‘admin’ user should be able to manage the site’s options – you need to specifically check if the current user actually has the manage_options capability.

For instance, generally you should avoid:

if ( current_user_can('admin') ) 
	// Do something that only users who can manage options should be able to do.

Instead, check the capability (or capabilities):

if ( current_user_can('manage_options') ) 
	// Do something that only users who can manage options should be able to do.

Add/Remove Capabilities

Adding and removing capabilities is very simple. WordPress provides the add_cap and remove_cap methods for the WP_Role object. For instance to add the capability ‘perform_xyz’ to the editor role:

	$editor = get_role('editor');
	$editor->add_cap('perform_xzy');

Similarly to remove a capability:

	$editor = get_role('editor');
	$editor->remove_cap('perform_xzy');

A role’s capabilities are stored in the database – so you only need to perform this once (for instance when your plug-in is activated or uninstalled).

If you want your plug-in to provide settings to allow users to edit other’s capabilities (capabilities that relate to your plug-in’s functionality) then a useful function is to use get_editable_roles() which returns a filtered array of roles. This shouldn’t be used instead of permission checks, but does allow your plugin user to restrict which roles can be edited by any given role. For instance, editors might be allowed to edit users – but only authors.

Meta Capabilities

The capabilities we’ve seen so far called ‘primitive’ capabilities – and these are assigned to various roles. Then there are meta capabilities, which are not assigned to roles, but instead map to primitive capabilities which are required of the current user’s role. For instance, given a post ID – we might want to ask does a user have the capability to edit this post?

if ( current_user_can('edit_post',61) ) 
	// Do something that only users who can edit post 61 should be able to do.

The edit_post capability isn’t assigned to any role (the primitive capability, edit_posts, however, is) – instead, WordPress checks which primitive roles this user requires in order to grant them permission to edit this post. For instance, if the current user is the post author they require the edit_posts capability. If they are not, they require the edit_others_posts capability. In both cases, if the post is published, they will also require the edit_published_posts capability. In this way meta capabilities are mapped to one or more primitive capabilities.

When you register a post type, by default the capabilities that are checked are the same as that for posts. However, you can specify your own capabilities:

register_post_type(
	'event',
	array(
		...
		'capabilities'=> array(
			// Meta capabilities
			'edit_post'=> 'edit_event',
			'read_post'=> 'read_event',
			'delete_post'=> 'delete_event',

			// Primitive capabilities
			'edit_posts'=> 'edit_events',
			'edit_others_posts'=> 'edit_others_events',
			'publish_posts'=> 'edit_others_events',
			'read_private_posts'=> 'read_private_events',
		),
		...
	)
);

Then to check if the current user has the permission to edit posts:

if ( current_user_can('edit_events') ) 
	// Do something that only users who can edit events should be able to do.

and to check if the current user can edit a particular event:

if ( current_user_can('edit_event',$post_id) ) 
	// Do something that only users who can edit $post_id should be able to do.

However – edit_event (like read_event and delete_event) is a meta capability, and so we need to map into the relevant primitive capabilities. To do so we use the map_meta_cap filter.

The logic is explained in the comments, but essentially we first check that the meta capability relates to our event post type, and that the passed post ID refers to an event. Next, we use a switch statement to deal with each meta capability and add roles to the $primitive_caps array. It’s these capabilities that the current user will need if they are to be granted permission – and exactly what they are dependant on the context.

add_filter('map_meta_cap', 'wptuts_event_meta_cap',10,4);

function wptuts_event_meta_cap( $primitive_caps, $meta_cap, $user_id, $args ) 
	// If meta-capability is not event based do nothing.
	if ( !in_array($meta_cap,array('edit_event','delete_event','read_event') ) 
		return $primitive_caps;
	

	// Check post is of post type.
	$post = get_post( $args[0] );
	$post_type = get_post_type_object( $post->post_type );
	if ( 'event' != $post_type ) 
		return $primitive_caps;
	

	$primitive_caps = array();

	switch( $meta_cap ):
		case 'edit_event':
			if ( $post->post_author == $user_id ) 
				// User is post author
				if ( 'publish' == $post->post_status ) 
					// Event is published: require 'edit_published_events' capability
					$primitive_caps[] = $post_type->cap->edit_published_posts;

				
				elseif ( 'trash' == $post->post_status ) 
					if ('publish' == get_post_meta($post->ID, '_wp_trash_meta_status', true) ) 
						// Event is a trashed published post require 'edit_published_events' capability
						$primitive_caps[] = $post_type->cap->edit_published_posts;
					

				}
				else 
					$primitive_caps[] = $post_type->cap->edit_posts;
				

			}
			else 
				// The user is trying to edit a post belonging to someone else.
				$caps[] = $post_type->cap->edit_others_posts;

				// If the post is published or private, extra caps are required.
				if ( 'publish' == $post->post_status ) 
					$primitive_caps[] = $post_type->cap->edit_published_posts;

				
				elseif ( 'private' == $post->post_status ) 
					$primitive_caps[] = $post_type->cap->edit_private_posts;
				
			}
			break;

		case 'read_event':
			if ( 'private' != $post->post_status ) 
				// If the post is not private, just require read capability
				$primitive_caps[] = $post_type->cap->read;

			
			elseif ( $post->post_author == $user_id ) 
				// Post is private, but current user is author
				$primitive_caps[] = $post_type->cap->read;

			
			else 
				// Post is private, and current user is not the author
				$primitive_caps[] = $post_type->cap->read_private_post;
			
			break;

		case 'delete_event':
			if ( $post->post_author == $user_id  ) 
				// Current user is author, require delete_events capability
				$primitive_caps[] = $post_type->cap->delete_posts;

			
			else 
				// Current user is no the author, require delete_others_events capability
				$primitive_caps[] = $post_type->cap->delete_others_posts;
			

			// If post is published, require delete_published_posts capability too
			if ( 'publish' == $post->post_status ) 
				$primitive_caps[] = $post_type->cap->delete_published_posts;
			
			break;

	endswitch;

	return $caps;
}

Returning to our front-end delete link, we want to add the following capability check. Add this just above the wp_trash_post call in wptuts_frontend_delete_post.

if ( ! current_user_can('delete_post',$post_id) )
	return;

Nonces

The above capability check ensures that only users who have permission to delete that post, are able to delete that post. But suppose someone tricks you into visiting that link. You have the necessary capabilities, so you unwittingly delete the post. Clearly we need to check that the current user intends to perform the action. We do this through nonces.

The analogy is that an attacker wants to hand some instructions to someone. Capability checks is the receiver demanding to see some ID first. But what if the attacker slips the instructions into your hand? The receiver will gladly carry them out (you, after all, have permission to make such instructions).

A nonce is like a seal on an envelope that verifies you were the actual sender. The seal is unique to each user, so if the attacker slipped those instructions into your hand, the receiver could inspect the seal and see it isn’t yours. However, seals can be forged – so a nonce changes every time you hand over instructions. This seal is ‘for the nonce‘ (hence the name) or in other words, temporary.

So if someone sends you the delete link, it will contain their nonce and so will fail the nonce check. Usually nonces are one use only, but WordPress’ implementation of nonces is slightly different: the nonce in fact changes every 12 hours, and each nonce is valid for 24 hours. You can change this with the nonce_life filter that filters the a nonce’s life in seconds (so normally 86400)

add_filter('nonce_life', 'wptuts_change_nonce_hourly');
function wptuts_change_nonce_hourly( $nonce_life ) 
	// Change nonce life to 1 hour
	return 60*60;

(but 24 hours should be sufficiently secure). More importantly, nonces should be unique to the instructions themselves, and any objects they relate to (e.g. deleting a post, and the post ID).

How Nonces Generated

WordPress takes a secret key (you can find it in your config file) and hashes it along with the following parts:

  • action – this uniquely identifies the action. This includes the action, and if applicable, the object ID you are applying the action to: e.g. for deleting the post with ID 61 we might set the nonce action to be wptuts_frontend_delete_61
  • user ID – ID which identifies the user ID. This makes the nonce unique to each user.
  • tick – The ‘tick’ marks progress in time. It increments every 12 hours (or half of what the nonce life is). This makes the nonce change every 12 hours.

To create a nonce, you can use wp_create_nonce($action) where $action is explained above. WordPress then appends the tick and user ID and hashes it with the secret key.

You then send this nonce along with the action and any other data you need to perform that action. Checking the nonce is very simple.

	// $nonce is the nonce value received with the action. $action is what we used to generate the nonce
	wp_verify_nonce($nonce, $action); // Returns true or false

where $nonce is the received nonce value and $action is the requested action as above. WordPress then generates the nonce using the $action and checks if it matches the given $nonce variable. If someone had sent you the link, their nonce will have been generated with their ID and so will be different to yours.

Alternatively, if the nonce was posted or added as a query variable, with name $name:

	check_admin_referer($action, $name);

If the nonce is invalid it will stop any further action and display a ‘Are you sure?‘ message.

WordPress makes it especially easy to use nonces: For forms you can use wp_nonce_field($action,$name). This generates a hidden field with name $name and the nonce generated form $action as its value.

For URLs you can use wp_nonce_url($url,$action). This takes the given $url and returns it with the the query variable _wpnonce added, with the generated nonce as its value.

In our example:

function wptuts_frontend_delete_link() 
	$url = add_query_arg(
		array(
			'action' => 'wptuts_frontend_delete',
			'post' => get_the_ID();
		)
	);

	$nonce = 'wptuts_frontend_delete_' . get_the_ID();

	echo  "Delete";

Which (for the post with ID 61) generates a nonce with action wptuts_frontend_delete_61. Then just above the trash call in wptuts_frontend_delete_post, we can check the nonce:

	check_admin_referer('wptuts_frontend_delete_'.$post_id, '_wpnonce');

Using Nonces in AJAX Requests

Using nonces in AJAX requests is slightly more involved. Nonces are generated server side, so the nonce value needs to printed as a javascript variable to be sent along with the AJAX request. To do this you can use wp_localize_script. Let’s suppose you have registered a script called wptuts_myjs which contains an AJAX request.

wp_enqueue_script('wptuts_myjs');
wp_localize_script(
	'wptuts_myjs',
	'wptuts_ajax',
	array(
		'url' => admin_url( 'admin-ajax.php' ), // URL to WordPress ajax handling page
		'nonce' => wp_create_nonce('my_nonce_action')
	)
);

Then inside our ‘wptuts_myjs’ script:

$.ajax(
	url: wptuts_ajax.url,
	dataType: 'json',
	data: 
		action: 'my_ajax_action',
		_ajax_nonce: wptuts_ajax.nonce,
	,
	...
});

Finally, inside your AJAX callback:

	check_ajax_referer('my_nonce_action');

Using More Than One Nonce

Normally one nonce per form (or per request) is sufficient. However, with WordPress the context is slightly complicated. For instance when you update a post, WordPress will perform permission and nonce checks – so presumably you don’t need to check a nonce for your function hooked onto save_post that deals with your custom meta box? Not so: save_post can be triggered in other instances, in various contexts or event manually – in fact whenever wp_update_post is called in fact. To be sure that the data you are receiving has come from your metabox you should use your own nonce. >

Of course if you are using more than one nonce in a form it’s important that you give your nonce a unique name – that is a unique name for the hidden field containing the nonce value. If multiple nonces in a form have the same name, one will over-ride the other and somewhere a check that should pass, fails.

So when creating a nonce for your metabox, make sure you give it a unique name:

function my_metabox_callback($post) 
	$name='my_nonce_name'; // Make sure this is unique, prefix it with your plug-in/theme name
	$action='my_action_xyz_'.$post->ID; // This is the nonce action

	wp_nonce_field($action,$name);

	// Your meta box...

Then for your save_post meta-box:

add_action('save_post','my_metabox_save_post');
function my_metabox_save_post( $post_id ) 
	// Check its not an auto save
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
		return;

	// Check your data has been sent - this helps verify that we intend to process our metabox
	if ( !isset($_POST['my_nonce_name']) )
		return;

	// Check permissions
	if ( !current_user_can('edit_post', $post_id) )
		return;

	// Finally check the nonce
	check_admin_referer('my_action_xyz_'.$post_id, 'my_nonce_name');

	// Perform actions

If you are dealing with data from more than one metabox – you should, ideally, have a nonce for each one. Meta boxes can be removed, and if the meta box containing the nonce is removed, then not even valid requests will pass. Consequently any processing of other metaboxes that rely on that nonce will not occur.


Aesthetics

Now only privileged users can delete posts – and we have methods in place to prevent attackers tricking them into visiting the link. Currently, however, the link appears for everyone – we should tidy this up so that it only appears for users who are allowed to use it! I’ve left this step last because hiding the link from unprivileged users has no security benefit whatsoever. Obscurity is not security.

We have to assume that the attacker is able to completely inspect the source code (be it WordPress, theme or plug-in) – and if so, simply hiding the link alone does nothing: they can simply construct the URL themselves. Capability checks prevent this, because, even with the URL, they do not have the cookies that give them permission. Also, nonces prevent them from tricking you into visiting the URL by requiring a valid nonce.

So, as a completely aesthetic exercise, we include a capability check inside the wptuts_frontend_delete_link() function:

function wptuts_frontend_delete_link() 
	if ( current_user_can('delete_post', get_the_ID()) ) 
		$url = add_query_arg(
			array(
				'action' => 'wptuts_frontend_delete',
				'post' => get_the_ID();
			)
		);

		echo  "Delete";
	}
}

Summary

It’s important to remember that capabilities indicate permission and nonces verify intention. Both are necessary to keep your plug-in secure, but one does not imply the other. Sometimes WordPress handles these checks for you – for instance when using the settings API. However, when hooking onto save_post it’s necessary to perform these checks.

Happy coding!

Original from: http://wp.tutsplus.com/tutorials/creative-coding/capabilities-and-nonces/

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

June 26th, 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 Facebook or 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.

Pondasee – Front-End Starter Kit

Pondasee - Front-End Starter Kit

Using Semantic HTML

Using Semantic HTML

The open/closed principle applied to CSS

The open/closed principle applied to CSS

A Look into: CSS3 Negation (:NOT) Selector

A Look into: CSS3 Negation (:NOT) Selector

Modular And Flexible Content In Responsive Design

Modular And Flexible Content In Responsive Design

Creating Custom Form Checkboxes and Radio Buttons with CSS

Creating Custom Form Checkboxes and Radio Buttons with CSS

Build a Mobile Template with Handlebars

Build a Mobile Template with Handlebars

Top 100 markup validation errors

Top 100 markup validation errors

Best Practices for Efficient HTML5 Coding

Best Practices for Efficient HTML5 Coding

CSS Generated Content on Replaced Elements

CSS Generated Content on Replaced Elements

HTML5: How to Use
and Tags

HTML5: How to Use <DETAILS> and <SUMMARY> Tags” /></a></p>
<h2><a target=Learning LESS: Put It Into Action

Learning LESS: Put It Into Action

Coding a Minimalist Contact Form with CAPTCHA Spam Protection

Coding a Minimalist Contact Form with CAPTCHA Spam Protection

The Boiler – Responsive HTML5/CSS3 Boilerplate WordPress theme

The Boiler - Responsive HTML5/CSS3 Boilerplate WordPress theme

CodePen

CodePen

ZeroBundle: A Great Bundle of Freebies for Designers

ZeroBundle: A Great Bundle of Freebies for Designers

Free Code Responsive Template

Free Code Responsive Template

WPApptouch – Free WordPress mobile theme

WPApptouch – Free WordPress mobile theme

Sketchkit Wireframes (Keynote)

Sketchkit Wireframes (Keynote)

Gaming and Cartoon GUI Pack

Gaming and Cartoon GUI Pack

Votes & Ratings UI Kit

Votes & Ratings UI Kit

Free CSS3 Button Styles – Vol 2

Free CSS3 Button Styles - Vol 2

Free Download: Sky UI Kit | Vandelay Design Blog

Free Download: Sky UI Kit | Vandelay Design Blog

Transparent Ui Kit

Transparent Ui Kit

Academic Icon Set

Academic Icon Set

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/i4z4Ta3p7gc/

Build a Slideshow Plugin for WordPress

June 25th, 2012 Comments off

Integrating slideshow functionality into WordPress is a highly required feature for almost any theme, but how hard is it to include and how flexible is it? In this tutorial we are going to, in different ways, include one of the most popular and used jQuery slideshows, Nivo Slider.

There is, actually, already a coded WordPress plugin for the Nivo Slider, right on the official Nivo Slider page. But we are going to build one in this tutorial anyway, and we are most definitely going to do it differently. In this tutorial we are going to create a Nivo slider plugin that will have widget functionality, short code functionality and you will even be able to integrate it as a simple function call and hard-code it into your theme where ever the user wishes.

By following this tutorial, it is implied that you are running an Apache and MySQL server locally or remotely in order to be able to install WordPress. Also, that you have a 3.1+ version of WordPress installed that you have access to its file system, and that you have basic PHP, CSS, JavaScript and HTML knowledge.


Step 1 Creating the Plugin

One of the easiest parts of this tutorial. We are going to create a folder named nivoplugin inside the wp-content/plugins directory inside your WordPress installation. Inside that directory we will create a nivoplugin.php file with the following code:


This is the basic plugin information used by WordPress to identify the plugin name and details. Things like Plugin Name, Description, Author and Plugin version are required parameters that are added as commented text at the top of each plugin so that WordPress can identify the plugin, manage it, run it and show the required information about it in the plugins page.

“For more information on plugin header text and other options that can be added to it please read Writing a Plugin in the WordPress Codex.”


Step 2 Creating the Admin Slideshow Management Functionality

The slideshow is made out of pictures, so in order to make a simple implementation of the jQuery Nivo Slider we need a way to add and manage pictures in the admin panel. Our approach is going to make good use of the custom post type WordPress functionality. Custom post types will be used to create a new custom page where each post contains all the required image details: the name and of course the most important part, the image itself. We are going to use the title and editor for the name and description information and the featured image functionality to upload the picture, manage and identify it.

function np_init() 
	$args = array(
		'public' => true,
		'label' => 'Nivo Images',
		'supports' => array(
			'title',
			'thumbnail'
		)
	);
	register_post_type('np_images', $args);

add_action('init', 'np_init');

In the above example we are adding a hook to the np_init function using the init hook tag that will run before the headers run. We need to do this so we can then include inside the register_post_type function with its parameters. This function is the function used to add and manage a new custom post type. Basically we include a new custom post type named np_images with some arguments.

The arguments are an array of values that represent the settings of that new custom post type. Things like if it is intended to be used publicly, we set public to true, we give it a label with the name Nivo Images and we set the fact that each post has a title and a featured image with the variables title and thumbnail as an array to the main attribute supports.

This creates the custom post type and it looks like this:

At this point we have a registered and working custom post type by the name of np_images. We can add new posts, delete them, and edit them as with regular posts, but custom made for our purpose to manage images for the slideshow. Basically this is the place where we add pictures for the Nivo slideshow as posts.


Step 3 Including the Nivo Slider Scripts and Styles

This might sound like something slightly complicated or time consuming a little more than usual. It’s not. We are going to download the free jQuery version of the Nivo Slider and include its necessary scripts and styles so that we may later use them with some custom code and images.

To download the sources we will go to the Pricing page on nivo.dev7studios.com and click on the jQuery Plugin (Free version) Download button on the left to download the sources.

For the purposes of this tutorial, we are going to keep things very simple. We unzip the file and include the whole directory inside our plugin directory. Inside the nivo-slider folder we have another folder named demo. We are going to delete that as we have no use for it and we don’t want a cluttered plugin with unnecessary stuff in it.

Registering and Including Scripts and Styles

The next part of this step is including the necessary Nivo Slider files. In our nivoplugin.php file we will add the following:

add_action('wp_print_scripts', 'np_register_scripts');
add_action('wp_print_styles', 'np_register_styles');

This is going to hook to some functions (the second parameter is the function name). We need these hooks to properly include the scripts and styles into the front-end. Let’s look at the callback functions of our previous hooks.

function np_register_scripts() 
	if (!is_admin()) 
		// register
		wp_register_script('np_nivo-script', plugins_url('nivo-slider/jquery.nivo.slider.js', __FILE__), array( 'jquery' ));
		wp_register_script('np_script', plugins_url('script.js', __FILE__));

		// enqueue
		wp_enqueue_script('np_nivo-script');
		wp_enqueue_script('np_script');
	
}

function np_register_styles() 
	// register
	wp_register_style('np_styles', plugins_url('nivo-slider/nivo-slider.css', __FILE__));
	wp_register_style('np_styles_theme', plugins_url('nivo-slider/themes/default/default.css', __FILE__));

	// enqueue
	wp_enqueue_style('np_styles');
	wp_enqueue_style('np_styles_theme');

The script callback function registers and includes 3 important javascript files: jQuery (as a dependancy of Nivo Slider), nivo-slider base file (jquery.nivo.slider.js) and our custom script file (script.js). Nivo Slider requires jQuery to work and we need a custom script to activate it.

The script.js File:

jQuery(document).ready(function($) 
	$('#slider').nivoSlider();
);

The script is pretty simple, it requires jQuery to attach the nivoSlider function to the tag with the id of slider. That tag is going to take the nivo-slider properties and functionality.

Lastly in our previous step, the style callback function registers and includes 2 more important files: the nivo-slider.css file that has all the styles needed to make the slider look and work accordingly, and a default.css file inside the themes/default folder that we use to theme the slideshow with the default nivo-slider theme.


Step 4 New Image Sizes

As mentioned in the beginning, this tutorial is going to cover the implementation of a widget, a shortcode and a function for hard-coding the slider if needed by using the plugin we are building. For the shortcode and function we need pretty much the same image sizes and for the widget a smaller size for the height and width of the images.

First, we must take into consideration the fact that we are using featured images in custom posts for our slideshow images. So how do we resize and crop those pictures to fit our required needs? We are going to add new image sizes that WordPress will resize and crop to on each new image upload. To add the new image sizes we will use the add_image_size function by adding the following code inside the np_init function:

	add_image_size('np_widget', 180, 100, true);
	add_image_size('np_function', 600, 280, true);

In the above source code we implemented 2 image sizes that we will call later on using the names np_widget for widget and np_function for shortcode and PHP function to identify them.

One More Thing

In order to enable post thumbnails in the plugin the following line of code needs to be added in our plugin. We are going to add it above the add_action lines.

	add_theme_support( 'post-thumbnails' );

“Image sizes added with add_image_size will only work for new pictures that are uploaded after the function is activated.”


Step 5 The PHP Function

One of the main features of the plugin is a PHP function that you can use anywhere in your theme code to insert the large 600×280 Nivo slideshow.

Because we are using custom posts to manage our pictures for the slideshow, we need to query those posts and get the titles and pictures from the custom post type. For that we are going to use a new WP_Query loop with the parameters of the $args variable that selects the custom post type and creates a slideshow of maximum 5 images from the query. Next we create a variable $result that has all the HTML code needed for the Nivo slideshow. We are using the demo HTML code wrappers from our Nivo script download folder.

function np_function($type='np_function') 
	$args = array(
		'post_type' => 'np_images',
		'posts_per_page' => 5
	);
	$result = '
'; $result .= '
'; //the loop $loop = new WP_Query($args); while ($loop->have_posts()) $loop->the_post(); $the_url = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), $type); $result .=''; $result .= '
'; $result .='
'; $result .='This is an example of a HTML caption with a link.'; $result .='
'; $result .='
'; return $result; }

Inside the loop we are using the wp_get_attachment_image_src function to retrieve the featured image from our custom post. We use the np_function value for the size of the image that we previously added in np_init. Because we are inside the loop, we can use $post->ID to identify the post. The function has one parameter, $type, that is used to set the images size from wp_get_attachment_image_src with one of the previously set image sizes. The variable has the default value of np_function. If no parameter is given when calling the function the default variable will kick in.

The titles of the posts are added as values to the title HTML parameter of the image tag and are visible at the bottom of the image slideshow as floating text over the images inside a transparent dark background.

The slider is automatically resized like the image sizes inside it, so whatever image sizes we use, we are going to have a slideshow of that size.

The slideshow in the np_function size looks like this:

This preview of the slideshow is the shortcode implementation that will be covered next.


Step 6 The Shortcode

Another main feature is the shortcode implementation. This is actually extremely easy to implement and can be done with one line of code. Just add this line in the np_init function above everything that is in there already:

	add_shortcode('np-shortcode', 'np_function');

The shortcode hook will actually use our PHP function to return the contents of the slideshow. That is all, very simple and fast implementation of the shortcode. To use it, just add [np-shortcode] in the content of any post or page. That text will be replaced with the actual slideshow.


Step 7 Building the Widget

In this step we are going to build a simple widget that will have the sole purpose of showing a small slideshow in the sidebar where ever it is placed.

We already have the size set for it in step 4 and we have all the other functionality that includes and generates the Nivo slideshow that we can use to integrate into the widget. So all that remains now is to build the widget and integrate the previous code.

function np_widgets_init() 
	register_widget('np_Widget');


add_action('widgets_init', 'np_widgets_init');

In this first part we are going to implement a new hook that you should add amongst the others. This hook uses the widgets_init tag and uses a function that we are going to name np_widgets_init. This function runs when the widgets are created. As a result we are going to register the widget under the name of np_Widget as in the example above.

The Class

To create a new widget, we are implementing a new class named np_Widget that extends the WP_Widget class. As a first function the __construct is the primary and most important function of the class and of our widget functionality. The function has parameters that we use to give the widget an unique ID that in our case is named np_widget, a name, Nivo Slideshow, and even a description as the following code shows:

class np_Widget extends WP_Widget 

	public function __construct() 
		parent::__construct('np_Widget', 'Nivo Slideshow', array('description' => __('A Nivo Slideshow Widget', 'text_domain')));
	
}

This is of course just the start of our widget, there are a few other functions we need to implement and configure as we need them to work.

Widget Backend

The widget looks as any other widget in the back end. We need to give the widget a title that has the possibility to be input by the user and later saved by the plugin. To do this we need to write the form function extended from the WP_Widget class. In this function we are going to use the $instance parameter that the function provides to get the title which is a variable later implemented, saved and updated. So we create the form input element using the following code:

	public function form($instance) 
		if (isset($instance['title'])) 
			$title = $instance['title'];
		
		else 
			$title = __('Widget Slideshow', 'text_domain');
		
		?>
			

This code runs only in the back end and is required by the following functions in order to submit the title name for saving and later use in the front end. The $instance variable has the value of the title and is used directly like the above example with no other query or function call.

Saving the Data

After the form is submitted from the previous function it needs to be processed and saved. This is done in the update function that we also need to add to the class with the following code:

	public function update($new_instance, $old_instance) 
		$instance = array();
		$instance['title'] = strip_tags($new_instance['title']);

		return $instance;
	

The value of the field is passed through the $new_instance variable that is stripped of tags, inserted in the $instance variable so that it can be returned by the function and saved by WordPress as part of its extended widget functionality.

Widget Front-End

Last but not least, another very important and also representative part of our widget is the front end functionality. Obviously, every piece is important for the end result to work, but this part is what you see in your theme.

The widget function is managing the front end of the widget and has two parameters: $args and $instance. The $args parameter is used to get variables like $before_widget, $after_widget and $before_title, $after_title that we are going to use in our implemented code. The widget function looks like this:

	public function widget($args, $instance) 
		extract($args);
		// the title
		$title = apply_filters('widget_title', $instance['title']);
		echo $before_widget;
		if (!empty($title))
			echo $before_title . $title . $after_title;
		echo np_function('np_widget');
		echo $after_widget;
	

To implement the slideshow we are using the function np_function but in this case we are giving it the parameter np_widget so that we get the image sizes we want for the widget.

This covers the widget implementation of the Nivo Slider in our plugin. At this point you can go into the admin panel and add a few posts in the Nivo images menu and attach featured images to them so that they appear in the slideshow.

“For more information about WordPress Widgets API check the WordPress Codex Widgets API.”


Conclusion

It’s very easy and fast to implement a slideshow in WordPress if you know what you are doing and especially if the slideshow functionality is already built and you are just integrating it. Still you have to be careful not to use some functionality that’s already there and of course, it’s easy if you implement it in a very basic manner like we just did, as a more flexible approach with many options and features might complicate things a little, depending on what the features are.

Original from: http://wp.tutsplus.com/tutorials/plugins/build-a-slideshow-plugin-for-wordpress/