The anatomy of a WordPress theme

Check out anatomy of a WordPress theme infographic:

Anatomy of a WordPress theme - Infographic

For reference, here is the copy in the infographic:

Anatomy of a WordPress theme

The cheatsheet for how your blog works

WordPress themes are made up of a folder of template files, each of which controls a specific piece of your theme. Parts of your site that remain static no matter what page you’re on are controlled by header, sidebar and footer files. You can hack these files so they detect what page you are on and serve different content accordingly, such as display different navigation on posts than on pages; however it is most common for these sections to look the same throughout the site.

  • header.php
    Global file that displays headers and navigation. Also contains HTML code.
  • The Loop
    The display of contents of the main area of your site are controlled by individual WordPress theme template files using what’s called “the loop”.
  • sidebar.php
    Sidebar display is controlled in this file. Multiple sidebars can be set up in functions.php, and contents of sidebar widgets are set up from the WordPress wp-admin panel.
  • footer.php
    Contains instructions for global footer and closes HTML tags.

index.php – home

The index file controls what the homepage of your WordPress theme looks like. By default it is a loop that queries and then displays the most recent blog posts, with a link in the bottom to view previous posts.

Alternately, you can specify in wp-admin -> settings -> reading to have the home page be a page you created yourself in WordPress. In that case, you specify a different page/URL for the regular blog posts to appear on, and that page is generated by index.php.

single.php – individual posts

The display of individual posts in your WordPress theme is controlled by a little file called single.php. It contains a loop that queries just one post and displays it.

You can specify if you want sidebars (and which you want), if you want it to look different than the other pages on the site.

page.php – individual pages

Page.php controls what pages look like. You can choose to eliminate sidebars or other elements, add other unique elements for pages alone.

WordPress also allows you to create different page templates within your WordPress theme for different types of pages. To create a page template, simply copy page.php, rename it to whatever you want, then add this code to the top:

1 <?php
2 /*
3 Template Name: YourPageNameHere
4 */
5 ?>

archive.php, category.php, tag.php – archives

You can control the look and feel of different archives using template files also. If there is no archive file, the archives will look like index.php; however you can create an archive.php to override that. If you create a file called category.php, it will override archive.php for categories only. If you create a tag.php, you can override it for tag archives only.

The Loop

The loop is perhaps the most powerful part of your WordPress theme. It starts with a query (which determines which posts or pages to grab), and ends with a PHP “endwhile” statement. Everything in between is up to you. You can specify the output of titles, post content, metadata, custom fields and commenting all within the loop and each element is output for each post or page until the query is done. You can set up multiple loops and queries on a single page; for example: on a single.php you could have the loop showing the entire content of a single post, with a loop outputting just titles and thumbnails for related posts below it.

  • Query post or page
  • Start Loop
  • the_title (outputs the title of the post)
  • the_excerpt (outputs the post excerpt)
  • the_content (outputs the full post content)
  • the_category (outputs the post categories)
  • the_author (outputs the post author)
  • the_date (outputs the post date)
  • other tags (there is a variety of other tags you can use in the loop)
  • endwhile;
  • Exit the loop

Background files of a WordPress theme

In order for a WordPress theme to work, it needs a few essential background files. These files can be modified to your needs and can quite powerfully affect the custom look and functionality of your site.

comments.php

This controls the output of comments, which can be included in the loop if you desire comments on your theme. Comments.php can be overriden by plugins such as Disqus, which then take over comment functionality on your blog.

functions.php

Functions.php allows you to put your own custom PHP code in order to modify core elements of your theme. It is often used to specify multiple sidebars, change the number of characters in the excerpt or add custom admin panel options for wp-admin.

style.css

This is the main CSS stylesheet for your theme. It also contains text at the top which tells WordPress what the name of your WordPress theme is, who the author is and what the URL of your site is.

Source: Yoast.com

How To Set Up a WordPress Ecommerce Website

This guide covers exactly how to set up a WordPress ecommerce website with the WooCommerce plugin.

The WordPress platform originally began as a way to blog online. Over the years, it has evolved into a full blown “content management system” – in other words, a backend software that can “power” any type of website – including an ecommerce website. Continue reading How To Set Up a WordPress Ecommerce Website

Creating Different CSS3 Box Shadows Effects

In this tutorial we are going to be creating box shadow effects with just CSS. Below is an image created in photoshop of different box shadows effects. These used to be the only way of creating this effect but thanks to CSS3 we can now do all this with just CSS.

 

View Demo page to see what we are going to create
CSS Box Shadow Effects Demo

Web Shadows Package

CSS Box Shadow

We are going to be using the CSS box shadow property which is one my favourite CSS properties which you will see in this tutorial how easy you can use it.

The box-shadow property allows you to easily create multiple drop shadows on box elements by specifying values for colour, size, blur and offset.

The box-shadow property accepts 2-6 options, the required options are horizontal offset and vertical offset, the two optional options are spread distance and colour.

box-shadow: inset horizontal vertical blur spread colour;

Examples

box-shadow: 10px 10px;
box-shadow: 10px 10px 5px #888;
box-shadow: inset 2px 2px 2px 2px black;
box-shadow: 10px 10px #888, -10px -10px #f4f4f4, 0px 0px 5px 5px #cc6600;

Browser Support

All of the major newest browsers support box-shadow property.

  • Internet Explorer 9.0 and higher
  • Firefox 3.5 and higher
  • Chrome 1 and higher
  • Safari 3 and higher
  • Opera 10.5 and higher

With many new CSS3 properties you need to prefix the property with browser specific tags.

For firefox you need to use -moz-, for chrome/safari you need to use -webkit.

The box-shadow property is no different.

For Firefox 3.5 you need to prefix with -moz-boz-shadow, but for Firefox 4.0 and higher you don’t need to use the prefix anymore.

For Chrome/safari you still need to use the -webkit-box-shadow.

For opera you don’t need to prefix the property and can just use box-shadow.

CSS Box Shadow Effect 1

CSS Box Shadow Effects1

This will create a standard box shadow effect with the shadow moved into the element to create a raised box look.

The HTML

<div class="box effect1">
	<h3>Effect 1</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}


/*==================================================
 * Effect 1
 * ===============================================*/
.effect1{
	-webkit-box-shadow: 0 10px 6px -6px #777;
	   -moz-box-shadow: 0 10px 6px -6px #777;
	        box-shadow: 0 10px 6px -6px #777;
}

CSS Box Shadow Effect 2

CSS Box Shadow Effects2

This effect will add shadows to the bottom corners of the boxes to create a lifted corner look on the boxes. This effect uses both the :before and :after properties to create new elements used for the corners.

The HTML

<div class="box effect2">
	<h3>Effect 2</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 2
 * ===============================================*/
.effect2
{
  position: relative;
}
.effect2:before, .effect2:after
{
  z-index: -1;
  position: absolute;
  content: "";
  bottom: 15px;
  left: 10px;
  width: 50%;
  top: 80%;
  max-width:300px;
  background: #777;
  -webkit-box-shadow: 0 15px 10px #777;
  -moz-box-shadow: 0 15px 10px #777;
  box-shadow: 0 15px 10px #777;
  -webkit-transform: rotate(-3deg);
  -moz-transform: rotate(-3deg);
  -o-transform: rotate(-3deg);
  -ms-transform: rotate(-3deg);
  transform: rotate(-3deg);
}
.effect2:after
{
  -webkit-transform: rotate(3deg);
  -moz-transform: rotate(3deg);
  -o-transform: rotate(3deg);
  -ms-transform: rotate(3deg);
  transform: rotate(3deg);
  right: 10px;
  left: auto;
}

CSS Box Shadow Effect 3

CSS Box Shadow Effects3

This uses half of the effect approve and will add a lifted corner to the bottom left of the box.

The HTML

<div class="box effect3">
	<h3>Effect 3</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 3
 * ===============================================*/
.effect3
{
  position: relative;
}
.effect3:before
{
  z-index: -1;
  position: absolute;
  content: "";
  bottom: 15px;
  left: 10px;
  width: 50%;
  top: 80%;
  max-width:300px;
  background: #777;
  -webkit-box-shadow: 0 15px 10px #777;
  -moz-box-shadow: 0 15px 10px #777;
  box-shadow: 0 15px 10px #777;
  -webkit-transform: rotate(-3deg);
  -moz-transform: rotate(-3deg);
  -o-transform: rotate(-3deg);
  -ms-transform: rotate(-3deg);
  transform: rotate(-3deg);
}

CSS Box Shadow Effect 4

CSS Box Shadow Effects4

Effect 4 will lift the corner on the bottom right of the box.

The HTML

<div class="box effect4">
	<h3>Effect 4</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 4
 * ===============================================*/
.effect4
{
  position: relative;
}
.effect4:after
{
  z-index: -1;
  position: absolute;
  content: "";
  bottom: 15px;
  right: 10px;
  left: auto;
  width: 50%;
  top: 80%;
  max-width:300px;
  background: #777;
  -webkit-box-shadow: 0 15px 10px #777;
  -moz-box-shadow: 0 15px 10px #777;
  box-shadow: 0 15px 10px #777;
  -webkit-transform: rotate(3deg);
  -moz-transform: rotate(3deg);
  -o-transform: rotate(3deg);
  -ms-transform: rotate(3deg);
  transform: rotate(3deg);
}

CSS Box Shadow Effect 5

CSS Box Shadow Effects5

This is expands on the effect 2 and will increase the angle of the shadows.

The HTML

<div class="box effect5">
	<h3>Effect 5</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 5
 * ===============================================*/
.effect5
{
  position: relative;
}
.effect5:before, .effect5:after
{
  z-index: -1;
  position: absolute;
  content: "";
  bottom: 25px;
  left: 10px;
  width: 50%;
  top: 80%;
  max-width:300px;
  background: #777;
  -webkit-box-shadow: 0 35px 20px #777;
  -moz-box-shadow: 0 35px 20px #777;
  box-shadow: 0 35px 20px #777;
  -webkit-transform: rotate(-8deg);
  -moz-transform: rotate(-8deg);
  -o-transform: rotate(-8deg);
  -ms-transform: rotate(-8deg);
  transform: rotate(-8deg);
}
.effect5:after
{
  -webkit-transform: rotate(8deg);
  -moz-transform: rotate(8deg);
  -o-transform: rotate(8deg);
  -ms-transform: rotate(8deg);
  transform: rotate(8deg);
  right: 10px;
  left: auto;
}

CSS Box Shadow Effect 6

CSS Box Shadow Effects6

This effect will create a curved shadow at the bottom of the box.

The HTML

<div class="box effect6">
	<h3>Effect 6</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 6
 * ===============================================*/
.effect6
{
  	position:relative;       
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect6:before, .effect6:after
{
	content:"";
    position:absolute; 
    z-index:-1;
    -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
    box-shadow:0 0 20px rgba(0,0,0,0.8);
    top:50%;
    bottom:0;
    left:10px;
    right:10px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
}

CSS Box Shadow Effect 7

CSS Box Shadow Effects7

This effect uses the previous effect and adds another shadow to the top of the box.

The HTML

<div class="box effect7">
	<h3>Effect 7</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 7
 * ===============================================*/
.effect7
{
  	position:relative;       
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect7:before, .effect7:after
{
	content:"";
    position:absolute; 
    z-index:-1;
    -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
    box-shadow:0 0 20px rgba(0,0,0,0.8);
    top:0;
    bottom:0;
    left:10px;
    right:10px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
} 
.effect7:after
{
	right:10px; 
    left:auto;
    -webkit-transform:skew(8deg) rotate(3deg); 
       -moz-transform:skew(8deg) rotate(3deg);     
        -ms-transform:skew(8deg) rotate(3deg);     
         -o-transform:skew(8deg) rotate(3deg); 
            transform:skew(8deg) rotate(3deg);
}

CSS Box Shadow Effect 8

CSS Box Shadow Effects8

The final effect will add rounded shadows to either side of the box.

The HTML

<div class="box effect8">
	<h3>Effect 8</h3>
</div>

The CSS

.box h3{
	text-align:center;
	position:relative;
	top:80px;
}
.box {
	width:70%;
	height:200px;
	background:#FFF;
	margin:40px auto;
}

/*==================================================
 * Effect 8
 * ===============================================*/
.effect8
{
  	position:relative;       
    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
}
.effect8:before, .effect8:after
{
	content:"";
    position:absolute; 
    z-index:-1;
    -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
    box-shadow:0 0 20px rgba(0,0,0,0.8);
    top:10px;
    bottom:10px;
    left:0;
    right:0;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
} 
.effect8:after
{
	right:10px; 
    left:auto;
    -webkit-transform:skew(8deg) rotate(3deg); 
       -moz-transform:skew(8deg) rotate(3deg);     
        -ms-transform:skew(8deg) rotate(3deg);     
         -o-transform:skew(8deg) rotate(3deg); 
            transform:skew(8deg) rotate(3deg);
}

Demo Page

View the demo page to see all these effects.

CSS Box Shadow Effects Demo

CSS Box Shadow Generator

To help people understand how these box shadows work, I’ve created a box shadow generator over at Coveloping. This has all the 8 different effects you see on this post and will allow you click on any of these effects to get the CSS code. Using the slider interface you can customise the look of these effects to anything you want.

Create your own CSS box shadows with this box shadow generator.

CSS Box Shadow Generator

CSS Box Shadow Generator

Continue reading Creating Different CSS3 Box Shadows Effects

How I Built The One Page Scroll Plugin

Scrolling effects have been around in web design for years now, and while many plugins are available to choose from, only a few have the simplicity and light weight that most developers and designers are looking for. Most plugins I’ve seen try to do too many things, which makes it difficult for designers and developers to integrate them in their projects.

Not long ago, Apple introduced the iPhone 5S, which was accompanied by a presentation website on which visitors were guided down sections of a page and whose messaging was reduced to one key function per section. I found this to be a great way to present a product, minimizing the risk of visitors accidentally scrolling past key information.

I set out to find a plugin that does just this. To my surprise, I didn’t find a simple solution to integrate in my current projects. That is when One Page Scroll was born.

What Is One Page Scroll?

One Page Scroll is a jQuery plugin that enables you to create a single-scroll layout for a group of sections on a page with minimal markup.

I will explain how I built this plugin, right from its inception through to planning, testing and finally putting the code out there for free.

Note: Before building this plugin, I was aware of the controversy over “scroll-hijacking,” whereby a website overrides the native scrolling behavior of the browser to create its own interaction, which confuses some visitors. One Page Scroll would inevitably go against this principle, so I decided to come up with ways to ease the frustration. One good thing about the plugin is that developers may set a fallback that reverts scrolling from its “hijacked” state to its native behavior for certain screen sizes. This way, developers can maintain the high performance and quality of their websites on low-power devices, such as smartphones and tablets. Other than that, you can also control the length of the animation that takes the visitor from one section to the next, thus allowing you to avoid the slow transition seen on Apple’s iPhone 5S website.

What Is Its Purpose?

As mentioned, most of the plugins that I found offer way too many unnecessary features, making them difficult to integrate. The purpose of this plugin is to solve this issue. The plugin had to:

  • be simple to use,
  • be easy to integrate,
  • require minimal markup,
  • do one thing well (i.e. scroll a page the way the iPhone 5S website does).

1. To The Drawing Board

I started by visualizing the plugin as a whole. It should enable visitors to scroll through each section of the page individually. To do that, I needed a way to disable the browser’s default scrolling behavior, while stacking each section in order and moving the page manually when the scrolling is triggered.

Visualize either in your mind or in sketches.
Visualize either in your mind or in sketches. (View large version)

After that, I broke the concept down into small tasks, trying to come up with a solution to each task in my mind. Here is a list of the functions and tasks that I came up with:

  1. Prepare the layout and position the sections.
    Disable the browser’s default scrolling behavior with CSS by applying overflow: hidden to the body tag. Position each section in sequence, while calculating and attaching all of the necessary information and classes.
  2. Set the manual scrolling trigger.
    Detect the scrolling trigger using jQuery, and then determine the direction, and then move the layout using CSS.
  3. Add features.
    Add responsiveness, looping, mobile swipe support, pagination, etc.
  4. Test across browsers.
    Make sure the plugin runs fine in all modern browsers (Chrome, Safari, Firefox, Internet Explorer 10) and on the most popular operating systems (Windows, Mac OS X, iOS and Android 4.0+).
  5. Open-source the plugin.
    Create a new repository, structuring it and writing instructions on how to use the plugin.
  6. Widen support.
    Explore other ways to increase support of the plugin.

2. Building The Foundation

Now that I had visualized the whole concept, I began to build the plugin with this template:

!function($) {

   var defaults = {
      sectionContainer: "section",};

   $.fn.onepage_scroll = function(options) {
      var settings = $.extend({}, defaults, options);}

}($)

The template starts off with a !function($) { … }($) module, which provides local scoping to the global variable for jQuery. The purpose of this function is to reduce the overhead for the jQuery lookup ($) and prevent conflicts with other JavaScript libraries.

The defaults variable at the top holds the default options for the plugin. So, if you don’t define any options, it will fallback to these values.

The $.fn.onepage_scroll function is the main function that initiates everything. Don’t forget to replace onepage_scroll with your own function name if you are creating your own.

Disabling the scrolling behavior can be done easily by adding overflow: hidden to the body tag via CSS through a plugin-specific class name. Coming up with a plugin-specific class naming convention is important to avoid conflicts with existing CSS styles. I usually go with an abbreviation of the plugin’s name, followed by a hyphen and a descriptive word: for example, .onepage-wrapper.

Now that all of the fundamentals are laid out properly, let’s build the first function.

3. Prepare The Layout And Position The Sections

Let’s get to the most interesting part: working out the calculation and instantly dropping all of my effort later in the process. I thought I needed to position each section in sequence by looping through each one and then positioning them, so that they do not overlap with each other. Here’s the snippet I came up with:

var sections = $(settings.sectionContainer);
var topPos = 0;

$.each(sections, function(i) {
   $(this).css({
      position: "absolute",
      top: topPos + "%"
   }).addClass("ops-section").attr("data-index", i+1);
   topPos = topPos + 100;
});

This snippet loops through each presented selector (sectionContainer is defined in the defaults variable), applies position: absolute and assigns each one with the correct top position that it needs to align properly.

The top position is stored in the topPos variable. The initial value is 0 and increases as it loops through each one. To make each section a full page and stack up correctly, all I had to do was set the height of each section to 100% and increase the topPos variable by 100 every time it loops through a section. Now, each section should stack up correctly, while only the first section is visible to visitors.

This might seem easy, but it took me a couple of hours to implement and to see how reliable it is, only to realize in the next step that I did not need any of this at all.

4. Manual Trigger And Page Transformation

You might think that the next step would be to move each section to its new position when the scrolling is triggered — I thought so, too. As it turns out, there is a better solution. Instead of moving every single section every time the user scrolls, which would require another loop through and another calculation, I wrapped all of the sections in one container and used CSS3’s translate3d to move the whole wrapper up and down. Because translate3d supports percentage-based values, we can use our previous top position calculation to move each section into the viewport without having to recalculate it. Another benefit is that this gives you control over the timing and easing settings of your animation.

As you may have noticed, this solution makes the positioning snippet illustrated in the previous step unnecessary because the wrapper that we’ve introduced makes each section stack up correctly without any extra styling required.

The first solution you come up with is not always the most efficient, so make sure to leave time for experimentation.
The first solution you come up with is not always the most efficient, so make sure to leave time for experimentation. (View large version)

Now, all we have to do is detect the direction of the user’s scrolling and move the wrapper accordingly. Here’s the code to detect the scrolling direction:

function init_scroll(event, delta) {
   var deltaOfInterest = delta,
   timeNow = new Date().getTime(),
   quietPeriod = 500;
   
   // Cancel scroll if currently animating or within quiet period
   if(timeNow - lastAnimation < quietPeriod + settings.animationTime) {
      event.preventDefault();
      return;
   }

   if (deltaOfInterest < 0) {
      el.moveDown()
   } else {
      el.moveUp()
   }
   lastAnimation = timeNow;
}

$(document).bind('mousewheel DOMMouseScroll', function(event) {
   event.preventDefault();
   var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail;
   init_scroll(event, delta);
});

In the snippet above, first I bind a function to the mousewheel event (or DOMMouseScroll for Firefox), so that I can intercept the scrolling data to determine the direction of the scrolling. By binding my own init_scroll function in these events, I’m able to pass the available wheelData to init_scroll and detect the direction.

In a perfect world, all I would have to do to detect and move each section is retrieve the delta from the wheelData variable, use the value to determine the direction and perform the transformation. That, however, is not possible. When you are dealing with a sequencing animation, you must create a fail-safe to prevent the trigger from doubling, which would cause the animation to overlap. We can use setInterval to sort this problem out by calling each animation individually, with its own time set apart to create a sequence. But for precision and reliability, setInterval falls short because each browser handles it differently. For example, in Chrome and Firefox, setInterval is throttled in inactive tabs, causing the callbacks not to be called in time. In the end, I decided to turn to a timestamp.

var timeNow = new Date().getTime(),
quietPeriod = 500;if(timeNow - lastAnimation < quietPeriod + settings.animationTime) {
   event.preventDefault();
   return;
}
…
lastAnimation = timeNow;

In the snippet above (extracted from the previous one), you can see that I have assigned the current timestamp to the timeNow variable before the detection, so that it can check whether the previous animation has performed for longer than 500 milliseconds. If the previous animation has performed for less than 500 milliseconds, then the condition would prevent the transformation from overlapping the ongoing animation. By using a timestamp, instead of setInterval, we can detect the timing more accurately because the timestamp relies on the global data.

if (deltaOfInterest < 0) {
   el.moveDown()
} else {
   el.moveUp()
}

The moveUp and moveDown are functions that change all attributes of the layout to reflect the current state of the website. Data such as the current index, the name of the current section’s class and so on are added in these functions. Each of these functions will call the final transform method to move the next section into the viewport.

$.fn.transformPage = function(settings, pos, index) {
   …
   $(this).css({
      "-webkit-transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)",
      "-webkit-transition": "all " + settings.animationTime + "ms " + settings.easing,
      "-moz-transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)",
      "-moz-transition": "all " + settings.animationTime + "ms " + settings.easing,
      "-ms-transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)",
      "-ms-transition": "all " + settings.animationTime + "ms " + settings.easing,
      "transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)",
      "transition": "all " + settings.animationTime + "ms " + settings.easing
   });}

Above is the transform method that handles the movement of each section. As you can see, I’ve used the CSS3 transformation to handle all of the manipulation with JavaScript. The reason I did this in JavaScript, rather than in a separate style sheet, is to allow developers to configure the behavior of the plugin — mainly the animation’s timing and easing — through their own function calls, without having to go into a separate style sheet and dig for the settings. Another reason is that the animation requires a dynamic value to determine the percentage of the transition, which can only be calculated in JavaScript by counting the number of sections.

5. Additional Features

I was reluctant to add features at first, but having gotten so much great feedback from the GitHub community, I decided to improve the plugin bit by bit. I released version 1.2.1, which adds a bunch of callbacks and loops and, hardest of all, responsiveness.

In the beginning, I didn’t focus on building a mobile-first plugin (which I still regret today). Rather, I used a simple solution (thanks to Eike Send for his swipe events) to detect and convert swipe data into usable delta data, in order to use it on my init_scroll function. That doesn’t always yield the best result in mobile browsers, such as custom Android browsers, so I ended up implementing a fallback option that lets the plugin fall back to its native scrolling behavior when the browser reaches a certain width. Here’s the script that does that:

var defaults = {
   responsiveFallback: false};

function responsive() {
   if ($(window).width() < settings.responsiveFallback) {
      $("body").addClass("disabled-onepage-scroll");
      $(document).unbind('mousewheel DOMMouseScroll');
      el.swipeEvents().unbind("swipeDown swipeUp");
   } else {
      if($("body").hasClass("disabled-onepage-scroll")) {
         $("body").removeClass("disabled-onepage-scroll");
         $("html, body, .wrapper").animate({ scrollTop: 0 }, "fast");
      }

      el.swipeEvents().bind("swipeDown",  function(event) {
         if (!$("body").hasClass("disabled-onepage-scroll")) event.preventDefault();
         el.moveUp();
      }).bind("swipeUp", function(event){
         if (!$("body").hasClass("disabled-onepage-scroll")) event.preventDefault();
         el.moveDown();
      });

      $(document).bind('mousewheel DOMMouseScroll', function(event) {
         event.preventDefault();
         var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail;
         init_scroll(event, delta);
      });
   }
}

First, I’ve defined a default variable to activate this fallback. The responsiveFallback is used to determine when the plugin should trigger the fallback.

The snippet above will detect the browser’s width to determine whether the responsive function should run. If the width reaches the value defined in responsiveFallback, then the function will unbind all of the events, such as swiping and scrolling, return the user to the top of the page to prepare for realignment of each section, and then reenable the browser’s default scrolling behavior so that the user can swipe through the page as usual. If the width exceeds the value defined, then the plugin checks for a class of disabled-onepage-scroll to determine whether it has already been initialized; if it hasn’t, then it is reinitialized again.

The solution is not ideal, but it gives the option for designers and developers to choose how to handle their websites on mobile, rather than forcing them to abandon mobile.

6. Cross-Browser Testing

Testing is an essential part of the development process, and before you can release a plugin, you must make sure that it runs well on the majority of machines out there. Chrome is my go-to browser, and I always start developing in it. It has many benefits as one’s main development browser, but your personal preference might vary. For me, Chrome has a more efficient inspection tool. Also, when I get a plugin to work in Chrome, I know that it will probably also work in Safari and Opera as well.

I mainly use my Macbook Air to develop plugins, but I also have a PC at home to check across platforms. When I get a plugin to work in Chrome, then I’ll test manually in Safari, Opera and (lastly) Firefox on Mac OS X, followed by Chrome, Firefox and Internet Explorer (IE) 10 on Windows.

The reason I test only these browsers is that the majority of users are on them. I could have tested IE 9 and even IE 8, but that would have prevented me from releasing the plugin in time with the launch of the iPhone 5S website.

This is generally not a good practice, and I’ll avoid doing it in future. But the good thing about making the plugin open-source is that other developers can help patch it after its release. After all, the purpose of an open-source project is not to create the perfect product, but to create a jumping-off point for other developers to extend the project to be whatever they want it to be.

Don’t forget to test on mobile devices before launching your plugin.
Don’t forget to test on mobile devices before launching your plugin. (View large version)

To ease the pain of cross-browser testing, every time I complete a plugin, I’ll create a demo page to show all of the features of the plugin, and then I’ll upload it to my website and test it, before sharing the plugin on GitHub. This is important because it enables you to see how the plugin performs in a real server environment and to squash any bugs that you might not be able to replicate locally. Once the demo page is up and running on my website, I’ll take the opportunity to test the plugin on other devices, such as phones and tablets.

With these tests, you will have covered the vast majority of browsers out there and prepared the plugin for the real world.

7. Open-Sourcing Your Plugin

When you think the plugin is ready, the final step is to share it on GitHub. To do this, create an account on GitHub, set up Git and create a new repository. Once that is done, clone the repository to your local machine. This should generate a folder with your plugin’s name on your local machine. Copy the plugin to the newly created folder and structure your repository.

Repository Structure

How you structure your repository is all up to you. Here’s how I do it:

  • The demo folder consists of working demos, with all required resources.
  • The minified and normal versions of the plugin are in the root folder.
  • The CSS and sample resources, such as images (if the plugin requires it), are in the root folder.
  • The readme file is in the root directory of the generated folder.

Readme Structure

Another important step is to write clear instructions for the open-source community. Usually, all of my instructions are in a readme file, but if yours require a more complex structure, you could go with a wiki page on GitHub. Here is how I structure my readme:

  1. Introduction
    I explained the purpose of the plugin, accompanied by an image and a link to the demo.
  2. Requirements and compatibility
    Put this up front so that developers can see right away whether they’ll want to use the plugin.
  3. Basic usage
    This section consists of step-by-step instructions, from including the jQuery library to adding the HTML markup to calling the function. This section also explains the options available for developers to play with.
  4. Advanced usage
    This section contains more complex instructions, such as any public methods and callbacks and any other information that developers would find useful.
  5. Other resources
    This section consists of links to the tutorial, credits, etc.

8. Widening Support

This plugin doesn’t really need the jQuery library to do what it does, but because of the pressure to open-source it in time for the iPhone 5S website, I decided to take a shortcut and rely on jQuery.

To make amends, and exclusively for Smashing Magazine’s readers, I have rebuilt One Page Scroll using pure JavaScript (a Zepto version is also available). With the pure JavaScript version, you no longer need to include jQuery. The plugin works right out of the box.

Pure JavaScript And Zepto Version

Rebuilding the Plugin in Pure JavaScript

The process of building support for libraries can seem daunting at first, but it’s much easier than you might think. The most difficult part of building a plugin is getting the math right. Because I had already done that for this one, transforming the jQuery plugin into a pure JavaScript one was just a few hours of work.

Because the plugin relies heavily on CSS3 animation, all I had to do was replace the jQuery-specific methods with identical JavaScript methods. Also, I took the opportunity to reorganize the JavaScript into the following standard structure:

  • Default variables
    This is essentially the same as the jQuery version, in which I defined all of the variables, including the default variables for options to be used by other functions.
  • Initialize function
    This function is used for preparing and positioning the layout and for the initialization that is executed when the onePageScroll function is called. All of the snippets that assign class names, data attributes and positioning styles and that bind all keyboard inputs reside here.
  • Private methods
    The private method section contains all of the methods that will be called internally by the plugin. Methods such as the swipe events, page transformation, responsive fallback and scroll detection reside here.
  • Public methods
    This section contains all of the methods that can be called manually by developers. Methods such as moveDown(), moveUp() and moveTo() reside here.
  • Utility methods
    This section contains all of the helpers that replicate a jQuery function to speed up development time and slim down the JavaScript’s file size. Helpers such as Object.extend, which replicates the jQuery.extend function, reside here.

I ran into some annoyances, such as when I had to write a method just to add or remove a class name, or when I had to use document.querySelector instead of the simple $. But all of that contributes to a better, more structured plugin, which benefits everyone in the end.

Rebuilding the Plugin in Zepto

The reason why I decided to support Zepto, despite the fact that it only supports modern browsers (IE 10 and above), is that it gives developers a more efficient and lightweight alternative to jQuery version 2.0 and above, with a more versatile API. Zepto’s file size (around 20 KB) is considerably lower than jQuery 2.0’s (around 80 KB), which makes a big difference in page-loading speed. Because websites are being accessed more on smartphones, Zepto might be a better alternative to jQuery.

Rebuilding a jQuery plugin with Zepto is a much easier task because Zepto is similar to jQuery in its approach to the API, yet faster and more lightweight. Most of the script is identical to the jQuery version except for the animation part. Because Zepto’s $.fn.animate() supports CSS3 animation and the animationEnd callback right off the bat, I can take out this ugly snippet:

$(this).css({
   "-webkit-transform": "translate3d(0, " + pos + "%, 0)",
   "-webkit-transition": "-webkit-transform " + settings.animationTime + "ms " + settings.easing,
   "-moz-transform": "translate3d(0, " + pos + "%, 0)",
   "-moz-transition": "-moz-transform " + settings.animationTime + "ms " + settings.easing,
   "-ms-transform": "translate3d(0, " + pos + "%, 0)",
   "-ms-transition": "-ms-transform " + settings.animationTime + "ms " + settings.easing,
   "transform": "translate3d(0, " + pos + "%, 0)",
   "transition": "transform " + settings.animationTime + "ms " + settings.easing
});
$(this).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(e) {
   if (typeof settings.afterMove == 'function') settings.afterMove(index, next_el);
});

And I’ve replaced it with this:

$(this).animate({
      translate3d: "0, " + pos + "%, 0"
   }, settings.animationTime, settings.easing, function() {
      if (typeof settings.afterMove == 'function') settings.afterMove(index, next_el);
   });
}

With Zepto, you can animate with CSS3 without having to define all of the CSS styles or bind the callback yourself. Zepto handles all of that for you through the familiar $.fn.animate() method, which works similar to the $.fn.animate() method in jQuery but with CSS3 support.

Why Go Through All the Trouble?

Because jQuery has become many people’s go-to library, it has also become increasingly complex and clunky and at times performs poorly. By providing versions for other platforms, you will increase the reach of your plugin.

Going back to the foundation will also help you to build a better, more compliant plugin for the future. jQuery and other libraries are very forgiving of minor structural problems, like missing commas and $(element) — the kinds of things that have made me a little lazy and could compromise the quality of my plugins. Without all of these shortcuts in pure JavaScript, I was more aware of what’s going on in my plugin, which methods are affecting performance and what exactly I can do to optimize performance.

Even though JavaScript libraries such as jQuery have made our lives easier, using one might not be the most efficient way to accomplish your goal. Some plugins are better off without them.

Conclusion

There you have it, the process I went through to build One Page Scroll. I made many mistakes and learned from them along the way. If I were to develop this plugin today, I would focus more on mobile-first and would add more comments to the code so that other people would be able to extend the plugin more easily.

Without the support of design and development communities such as GitHub, StackOverflow and, of course, Smashing Magazine, I wouldn’t have been able to create this plugin in such a short time. These communities have given me so much in the past few years. That is why One Page Scroll and all of my other plugins are open-source and available for free. That’s the best way I know how to give back to such an awesome community.

I hope you’ve found this article useful. If you are working on a plugin of your own or have a question or suggestion, please feel free to let us know in the comments below.

Resources

Source: http://www.smashingmagazine.com/

Move, Rename WordPress wp-content and Plugins Directory

WordPress Logo

WordPress has a feature which gives you the ability to relocate and rename the “wp-content” directory that holds the themes, plugins and uploaded files used by your blog. Moving this directory is good from a security perspective too.

Here I will show how you can move the wp-content and plugins directory to a custom location on your web server.

Move WordPress wp-content directory

To move the wp-content directory, add the below two define() directives to your WordPress wp-config.php (configuration) file, replacing with appropriate paths on your server.

/* Move wp-content directory */
define('WP_CONTENT_DIR', 'new/path/to/wp-content'); // no host name, no trailing backslash
define('WP_CONTENT_URL', '/url/to/wp-content');

The WP_CONTENT_DIR, is used to specify the actual path of the content directory on your server, while the WP_CONTENT_URL speficies the URL through which the contents inside the directory can be accessed.

If you are not sure about the exact path, here’s another way to define path using the$_SERVER[‘DOCUMENT_ROOT’] and $_SERVER[‘SERVER_NAME’] global variable:

/* Move wp-content directory */
define('WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/content');
define('WP_CONTENT_URL', 'http://' . $_SERVER['SERVER_NAME'] . '/content');

The $_SERVER[‘DOCUMENT_ROOT’] will construct a path relative to the document root, while $_SERVER[‘SERVER_NAME’] does the same for your web server.

Move WordPress Plugin Directory

If you want to move the WordPress plugins directory to a custom location, you have to definePLUGIN_DIR in your configuration file, similar to how CONTENT_DIR is defined for wp-content:

/* Move plugins directory */
 define('WP_PLUGIN_DIR', 'new/path/to/plugins');
 define('WP_PLUGIN_URL', '/url/to/plugins');

OR

/* Move plugins directory */
define('WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/plugins' );
define('WP_PLUGIN_URL', 'http://' . $_SERVER['SERVER_NAME'] . '/plugins');

Defining path to WordPress plugins folder may also help you resolve problems with those plugins that have a hardcoded path to wp-content.

If at any time you wish to go back to the original structure, simply delete the above added lines from wp-config.php file and move back the folders to the original locations.

 

Source: http://sumtips.com/

Create Native Admin Tables In WordPress The Right Way | Smashing WordPress

List tables are a common element in WordPress’ administration interface. They are used on nearly all default admin pages with lists, and developers often integrate them into their plugins. But creating one of these tables is not really intuitive if you haven’t done it before, and I’ve seen people try to replicate it by using WordPress CSS classes in custom markup and even by replicating the CSS from scratch.

In this article, we’ll see how WordPress provides functionality that can be used to generate native admin tables. We’ll look at a typical WordPress table and its different components and show how to implement it the right way.

Presentation Of A WordPress Table

To better understand the various elements we’ll be talking about, let’s take the default link manager that you see when you click “Links” in the admin menu. Here’s what you see:

The default page for managing links in WordPress 3.2.

As you can see, a few different elements precede the table that enable you to perform actions on the table. Then we have the table’s header, the rows, the table’s footer and, finally, some more actions.

BEFORE AND AFTER THE TABLE

WordPress’ admin interface is consistent, so you’ll get used to finding elements in certain places as you navigate.

Before and after the admin tables, for example, are where you would usually find options to take action on the table. These include bulk actions, which enable you to edit and delete multiple posts and to filter the list based on a certain criteria.

We’ll see in the second part of this article how to interact with these two areas and how to display options there.

HEADER AND FOOTER

Speaking of consistency, every admin table in WordPress has a header and footer.

Following the same logic, they display the the same information: the titles of the columns. Some of the titles are simple and some are linked (meaning that the table can be ordered according to that column).

THE CONTENT

Obviously, the reason you would create a table is to put some content in it. This content would go in the rows between the header and footer.

How Is This Done In WordPress?

As we’ve just seen, a WordPress table has three families of elements. Let’s see how to achieve this, using a concrete example.

OUR EXAMPLE TABLE

Most of the time, the data we want to display will be in the form of a SQL table. We’ll use the default links table in WordPress as our example, but the concepts apply to any database table and could easily be adapted to your needs. Our table will have the following structure:

This table contains some default data that will be perfect for testing.

USING THE LIST TABLE CLASS

To create an HTML table in WordPress, we don’t have to write a lot of HTML. Instead, we can rely on the precious work of the WP_List_Table class. As explained by the WordPress Codex, this class is a powerful tool for generating tables.

It is tailored for back-end developers, so we can concentrate on the most essential task (the treatment of the data), leaving the other tasks (such as HTML rendering) to WordPress.

The WP_List_Table class is essentially a little framework whose functionality we can rely on to prepare our table. This is an object-oriented approach, because we’ll be creating an object that extends WP_List_Table and using that, instead of using WP_List_Table directly.

Let’s create a class Link_List_Table with a simple constructor:

01 class Link_List_Table extends WP_List_Table {
02
03     /**
04      * Constructor, we override the parent to pass our own arguments
05      * We usually focus on three parameters: singular and plural labels, as well as whether the class supports AJAX.
06      */
07      function __construct() {
08          parent::__construct( array(
09         'singular'=> 'wp_list_text_link', //Singular label
10         'plural' => 'wp_list_test_links', //plural label, also this well be one of the table css class
11         'ajax'  => false //We won't support Ajax for this table
12         ) );
13      }
14
15 }

This is the starting point of our table. We now have an object that has access to the properties and methods of its parent, and we’ll customize it to suit our needs.

Keeping in mind the three types of elements we saw earlier, let’s see now what to add to our class to get the same result.

HOW TO ADD ELEMENTS BEFORE AND AFTER THE TABLE

To display content before or after the table, we need to add a method namedextra_tablenav to our class. This method can be implemented as follows:

01 /**
02  * Add extra markup in the toolbars before or after the list
03  * @param string $which, helps you decide if you add the markup after (bottom) or before (top) the list
04  */
05 function extra_tablenav( $which ) {
06     if ( $which == "top" ){
07         //The code that goes before the table is here
08         echo"Hello, I'm before the table";
09     }
10     if ( $which == "bottom" ){
11         //The code that goes after the table is there
12         echo"Hi, I'm after the table";
13     }
14 }

The interesting thing here is that the extra_tablenav method takes one parameter, named$which, and this function is called twice by Link_List_Table, (once before the table and once after). When it’s called before, the value of the $which parameter is top, and when it’s called a second time, after the table, its value is bottom.

You can then use this to position the various elements that you’d like to appear before and after the table.

This function exists in the parent WP_List_Table class in WordPress, but it doesn’t return anything, so if you don’t override it, nothing bad will happen; the table just won’t have any markup before or after it.

HOW TO PREPARE THE TABLE’S HEADER AND FOOTER

In the header and footer, we have the column’s headers, and some of them are sortable.

We’ll add to our class a method named get_columns that is used to define the columns:

01 /**
02  * Define the columns that are going to be used in the table
03  * @return array $columns, the array of columns to use with the table
04  */
05 function get_columns() {
06     return $columns= array(
07         'col_link_id'=>__('ID'),
08         'col_link_name'=>__('Name'),
09         'col_link_url'=>__('Url'),
10         'col_link_description'=>__('Description'),
11         'col_link_visible'=>__('Visible')
12     );
13 }

The code above will build an array in the form of 'column_name'=>'column_title'. This array would then be used by your class to display the columns in the header and footer, in the order you’ve written them, so defining that is pretty straightforward.

Plenty of fields are in the links table, but not all of them interest us. With our get_columnsmethod, we’ve chosen to display only a few of them: the ID, the name, the URL, the description of the link, as well as whether the link is visible.

Unlike the extra_tablenav method, the get_columns is a parent method that must be overridden in order to work. This makes sense, because if you don’t declare any columns, the table will break.

To specify the columns to which to add sorting functionality, we’ll add the get_sortablecolumns method to our class:

01 /**
02  * Decide which columns to activate the sorting functionality on
03  * @return array $sortable, the array of columns that can be sorted by the user
04  */
05 public function get_sortable_columns() {
06     return $sortable = array(
07         'col_link_id'=>'link_id',
08         'col_link_name'=>'link_name',
09         'col_link_visible'=>'link_visible'
10     );
11 }

Here again, we’ve built a PHP array. The model for this one is'column_name'=>'corresponding_database_field'. In other words, the column_name must be the same as the column name defined in the get_columns method, and thecorresponding_database_field must be the same as the name of the corresponding field in the database table.

The code we have just written specifies that we would like to add sorting functionality to three columns (“ID,” “Name” and “Visible”). If you don’t want the user to be able to sort any columns or if you just don’t want to implement this method, WordPress will just assume that no columns are sortable.

At this point, our class is ready to handle quite a few things. Let’s look now at how to display the data.

HOW TO DISPLAY THE TABLE’S ROWS

The first steps in preparing the list table are very quick. We just have to tackle a few more things in the treatment of data.

To make the list table display your data, you’ll need to prepare your items and assign them to the table. This is handled by the prepare_items method:

01 /**
02  * Prepare the table with different parameters, pagination, columns and table elements
03  */
04 function prepare_items() {
05     global $wpdb, $_wp_column_headers;
06     $screen = get_current_screen();
07
08     /* -- Preparing your query -- */
09         $query = "SELECT * FROM $wpdb->links";
10
11     /* -- Ordering parameters -- */
12         //Parameters that are going to be used to order the result
13         $orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : 'ASC';
14         $order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : '';
15         if(!empty($orderby) & !empty($order)){ $query.=' ORDER BY '.$orderby.' '.$order; }
16
17     /* -- Pagination parameters -- */
18         //Number of elements in your table?
19         $totalitems = $wpdb->query($query); //return the total number of affected rows
20         //How many to display per page?
21         $perpage = 5;
22         //Which page is this?
23         $paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : '';
24         //Page Number
25         if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; }
26         //How many pages do we have in total?
27         $totalpages = ceil($totalitems/$perpage);
28         //adjust the query to take pagination into account
29         if(!empty($paged) && !empty($perpage)){
30             $offset=($paged-1)*$perpage;
31             $query.=' LIMIT '.(int)$offset.','.(int)$perpage;
32         }
33
34     /* -- Register the pagination -- */
35         $this->set_pagination_args( array(
36             "total_items" => $totalitems,
37             "total_pages" => $totalpages,
38             "per_page" => $perpage,
39         ) );
40         //The pagination links are automatically built according to those parameters
41
42     /* -- Register the Columns -- */
43         $columns = $this->get_columns();
44         $_wp_column_headers[$screen->id]=$columns;
45
46     /* -- Fetch the items -- */
47         $this->items = $wpdb->get_results($query);
48 }

As you can see, this method is a bit more complex than the previous ones we added to our class. So, let’s see what is actually happening here:

  1. Preparing the query
    The first thing to do is specify the general query that will return the data. Here, it’s a generic SELECT on the links table.
  2. Ordering parameters
    The second section is for the ordering parameters, because we have specified that our table can be sorted by certain fields. In this section, we are getting the field (if any) by which to order our record ($_GET['order']) and the order itself ($_GET['orderby']). We then adjust our query to take those into account by appending an ORDER BY clause.
  3. Pagination parameters
    The third section deals with pagination. We specify how many items are in our database table and how many to show per page. We then get the current page number ($_GET['paged']) and then adapt the SQL query to get the correct results based on those pagination parameters.
  4. Registration
    This part of the function takes all of the parameters we have prepared and assigns them to our table.
  5. Ready to go
    Our list table is now set with all of the information it needs to display our data. It knows what query to execute to get the records from the database; it knows how many records will be returned; and all the pagination parameters are ready. This is an essential method of your list table class. If you don’t implement it properly, WordPress won’t be able to retrieve your data. If the method is missing in your class, WordPress will return an error telling you that the prepare_items method must be overridden.
  6. Displaying the rows
    This is it! Finally, we get to the method responsible for displaying the records of data. It is named display_rows and is implemented as follows.
01 /**
02  * Display the rows of records in the table
03  * @return string, echo the markup of the rows
04  */
05 function display_rows() {
06
07     //Get the records registered in the prepare_items method
08     $records = $this->items;
09
10     //Get the columns registered in the get_columns and get_sortable_columns methods
11     list( $columns, $hidden ) = $this->get_column_info();
12
13     //Loop for each record
14     if(!empty($records)){foreach($records as $rec){
15
16         //Open the line
17         echo '< tr id="record_'.$rec->link_id.'">';
18         foreach ( $columns as $column_name => $column_display_name ) {
19
20             //Style attributes for each col
21             $class = "class='$column_name column-$column_name'";
22             $style = "";
23             if ( in_array( $column_name, $hidden ) ) $style = ' style="display:none;"';
24             $attributes = $class . $style;
25
26             //edit link
27             $editlink  = '/wp-admin/link.php?action=edit&link_id='.(int)$rec->link_id;
28
29             //Display the cell
30             switch ( $column_name ) {
31                 case "col_link_id": echo '< td '.$attributes.'>'.stripslashes($rec->link_id).'< /td>';   break;
32                 case "col_link_name": echo '< td '.$attributes.'><strong><a href="'.$editlink.'" title="Edit">'.stripslashes($rec->link_name).'</a></strong>< /td>'; break;
33                 case "col_link_url": echo '< td '.$attributes.'>'.stripslashes($rec->link_url).'< /td>'; break;
34                 case "col_link_description": echo '< td '.$attributes.'>'.$rec->link_description.'< /td>'; break;
35                 case "col_link_visible": echo '< td '.$attributes.'>'.$rec->link_visible.'< /td>'; break;
36             }
37         }
38
39         //Close the line
40         echo'< /tr>';
41     }}
42 }

This function gets the data prepared by the prepare_items method and loops through the different records to build the markup of the corresponding table row.

With this method, you have great control over how to display the data. If you do not wish to add this method to your class, then the class will use the parent’s method to render the data in WordPress’ default style.

Your list table class is now finished and ready to be used on one of your pages.

All of the methods we’ve added to our class already exist in the parent WP_List_Tableclass. But for your child class to work, you must override at least two of them: get_columnsand prepare_items.

Implementation

Now that our list table class is ready, let’s see how we can use it on a page of our choice.

WHERE DO WE WRITE IT?

The code that we’ll cover in this section has to be written on the page where you want to display the admin table.

We’ll create a very simple demonstration plugin, named “Test WP List Table.” Basically, this plugin will add a link in the WordPress “Plugins” sub-menu. Our code will, therefore, be written in the plugin file.

BEFORE WE BEGIN

Important: the WP_List_Table class is not available in plugins by default. You can use the following snippet to check that it is there:

1 //Our class extends the WP_List_Table class, so we need to make sure that it's there
2 if(!class_exists('WP_List_Table')){
3     require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
4 }

Also, if you have created your Links_List_Table class in an external file, make sure to include it before you start instantiating.

INSTANTIATE THE TABLE

The first step is to create an instance of our list table class, then call the prepare_itemsmethod to fetch the data to your table:

1 //Prepare Table of elements
2 $wp_list_table = new Links_List_Table();
3 $wp_list_table->prepare_items();

DISPLAY IT

The $wp_list_table object is now ready to display the table wherever you want.

Build your page’s markup, and wherever you decide to display the table, make a call to thedisplay() method:

1 //Table of elements
2 $wp_list_table->display();

Calling the display() method will generate the full markup of the list table, from the before-and-after area to the table’s content, and including the table’s header and footer. It also automatically generates all pagination links for you, so the result should look like this:

In the download accompanying this article, you’ll find the complete PHP file containing the class definition and the example of its implementation. It is named testWPListTable.php, and it is written in the form of a simple plugin that you can put in your WordPress plugin folder and activate if you want to see what it does.

Conclusion

Creating a PHP class merely to display a table of data might seem like overkill. But this class is very easy to create and customize. And once it’s done, you’ll be happy that the parts of tables that are difficult to implement, such as pagination and reordering, are now taken care of.

Also, because the generated markup is exactly what WordPress supports, if an update is released one day, your tables will remain in good shape.

The PHP code we’ve used is clean and easy to understand. And mastering the default functionality won’t take a long time.

What we’ve seen today is the basic implementation of a WordPress list table, but you can add other supported methods to the class for extra functionality.

For more information, read the Codex page dedicated to WordPress list tables, and have a look at another custom list table example.

I hope you’ve found this article useful, and I wish you good luck with list tables!

(al)

Source: http://wp.smashingmagazine.com/2011/11/03/native-admin-tables-wordpress/

Useful jQuery Function Demos For Your Projects

Every aspiring Web developer should know about the power of JavaScript and how it can be used to enhance the ways in which people see and interact with Web pages. Fortunately, to help us be more productive, we can use the power of JavaScript libraries, and in this article we will take a good look at jQuery in action.

What Is jQuery?

In a nutshell, jQuery is a leading JavaScript library that can perform wonders on your Web pages and make your Web development life much easier and more enjoyable. With the rise in popularity of jQuery since its arrival in 2006, over an estimated 24 million websites (50% of them being the 10,000 most visited websites) currently reap the benefits, and as Google Trends suggests, it’s the most popular JavaScript library.

Thousands of Web developers worldwide use jQuery to innovate on their websites and stay up to date on trends. This surge has been influenced by several jQuery gurus who have helped make jQuery what is today. I would like to personally thank these guys and gals for their hard work and would like to do my part to spread the news about JavaScript and jQuery. In this article, we’ll show you over 50 of jQuery’s most renowned functions, demonstrated with live visual examples. The jQuery library is comprehensive, so hopefully seeing these most frequently used functions in action will improve your understanding of how they can work together to produce excellent results.

jQuery And CSS

Styles play a big part in the look and feel of any website, and jQuery can help us change them dynamically. In this section, we will look at how jQuery can be used to dynamically add and remove style classes and entire cascading style sheets.

.css()

You can change your website’s styles dynamically with jQuery’s .css() 1 function. Either change styles that are already declared inline or in CSS files (such as font-size, color, background-color, etc.) or create new styles for elements.

Demo: Change text color and background color

Blue text with orange background

Launch Demo

Demo: Add a style sheet

.addClass() and .toggleClass()

In addition to the .css() function, you can apply currently defined CSS classes by using the .addClass() 2 function. Its counterpart function, .removeClass(), reverses the action.

Demo: Add a CSS class to an element

Click “Run demo” to add the styles to the button. Click “Reset” to remove the styles.

Launch Demo

The .toggleClass() 3 function is a huge time-saver for toggling a state on and off with CSS. The following example sets event handlers for mouseenter (which applies the CSS class img-hover to the image) and mouseleave (which removes it).

Demo: Toggle a CSS class on an element

jQuery Animations And Effects

We can use jQuery to create some very smooth animations and effects with minimal effort. Animations and effects are always best demonstrated with examples, so let’s dive right in.

.animate()

The .animate() 4 function can be used to animate the movement and/or appearance of elements on a Web page. Let’s look at both. You may define the settings parameter with a set duration (in milliseconds) or any of the words slow, normal or fast. The callback, which is the function that runs after the animation has finished, is optional.

Demo: Animate text

Demo: Animate size

Easily change the size of a div.

Demo: Animate movement

The .animate() function is asynchronous, so multiple animations may run at the same time. You can also use the .stop() function to stop the animation. If you click “Run demo” and then “Reset” during the animation, it will demonstrate the .stop() function.

Many pure JavaScript functions are used frequently in animations, such as setInterval(), clearInterval(), setTimeout() and clearTimeout(). Once again, these functions are included in the list because understanding what they can do is important to supporting the jQuery’s animation functions.

setInterval() and clearInterval()

You can automate a task based on time using the JavaScript setInterval() function, which can be used to specify a regular time-based trigger.

Demo: Simple time counter

Click “Run demo” to start the timer, and click “Reset” to stop it.

0 seconds elapsed

Launch Demo

Demo: Digital time display

setTimeout() and clearTimeout()

You can also delay a task based on time using the JavaScript setTimeout() function, which can be set to wait for a specified length of time before running the code.

Demo: Do something after a specified length of time.

Click “Run demo” to set the timeout and, click “Reset” to clear it.

This text will disappear after three seconds.

Launch Demo

.slideToggle() and .fadeToggle()

jQuery provides various toggle functions that save us heaps of time when we want to bind related events to the same element. For example, .slideToggle() 5 binds both .slideUp() 6 and .slideDown() 7 to the element and also manages that state for us.

Demo: Slide an element in and out of view.

Click “Run demo” to show the paragraph, and click again to hide.

Curabitur placerat commodo augue eget congue. Aliquam id ante leo. Duis at libero magna, at dignissim odio. Aliquam aliquet suscipit mollis. Pellentesque libero tortor, elementum id mattis vel, mattis eget metus. Nam convallis interdum imperdiet. Fusce at magna tellus. Sed mi ante, aliquam at accumsan ac, tristique sit amet dui. Aliquam eleifend molestie ligula. Vivamus eleifend, diam id tincidunt posuere, ipsum dui elementum sapien, posuere pulvinar risus neque id turpis. Nullam volutpat cursus libero, sit amet euismod justo eleifend vitae.

Launch Demo

The .fadeToggle() function is similar to .slideToggle() but with a fading effect that uses the .fadeIn() and .fadeOut() methods.

Demo: Fade an element in and out of view.

Click “Run demo” to show the paragraph, and click again to hide it.

Curabitur placerat commodo augue eget congue. Aliquam id ante leo. Duis at libero magna, at dignissim odio. Aliquam aliquet suscipit mollis. Pellentesque libero tortor, elementum id mattis vel, mattis eget metus. Nam convallis interdum imperdiet. Fusce at magna tellus. Sed mi ante, aliquam at accumsan ac, tristique sit amet dui. Aliquam eleifend molestie ligula. Vivamus eleifend, diam id tincidunt posuere, ipsum dui elementum sapien, posuere pulvinar risus neque id turpis. Nullam volutpat cursus libero, sit amet euismod justo eleifend vitae.

Launch Demo

.delay()

In this demonstration, we’ll mainly use jQuery’s awesome function-chaining ability by running the .fadeOut(), .fadeIn() and .delay() functions together on the same element. This is very similar to the setTimeout() function we saw earlier but without allowing us to easily interrupt the delay.

Demo: Use .delay() to create a delay between function calls.

jQuery And DOM Manipulation

The DOM (document object model) is all of the HTML content that you see on a website (text, images, container elements, etc.). We can use jQuery to perform wonders with the DOM when all page elements have been loaded. The event that captures when the DOM is ready is called .ready(), and there are a few ways to call it. In this section are demos of jQuery functions that change the DOM in some way.

.clone()

The jQuery .clone() function is pretty simple to use; it basically just copies the element that you specify into a new element.

Demo: Clone an element.

.html(), .text() and .empty()

Using .html() 8 is the most common way to get or set the content of an element using jQuery. If you just want the text and not the HTML tags, you can use .text() 9, which will return a string containing the combined text of all matched elements. These functions are browser-dependent (i.e. .html() uses the browser’s innerHTML property), so the results returned (including white space and line breaks) will always depend on the browser you are using.

In this example, we are also making use of the .empty() 10 function, which is a quick way to get rid of the content within, and .prev(), which can be used to reference the preceding element, in this case the demo buttons.

Demo: Get the content of an element.

.append(), prepend(), .after() and .before()

These function provide the means of inserting content in particular places relative to elements already on the Web page. Although the differences may appear trivial, each has its own purpose, and knowing exactly where they will all place content will save you coding time.

Demo: Insert content onto a Web page.

txt = ‘This is the content we wish to insert.‘innerDiv.append(txt) | innerDiv.prepend(txt) | innerDiv.after(txt) | innerDiv.before(txt)

outerDiv

innerDiv

Launch Demo

jQuery And AJAX

The jQuery library has a full suite of AJAX capabilities that enables us to load data from a server without refreshing the browser page. In this section, we will have a quick look at refreshing page content, loading scripts and retrieving data from different Web pages and servers.

$.ajax()

The $.ajax() 11 function is arguably the most used jQuery function. It gives us a means of dynamically loading content, scripts and data and using them on a live Web page. Other common uses are submitting a form using AJAX and sending data to server-side scripts for storing in a database.

The $.ajax() function has a lot of settings, and the kind team at jQuery has provided many shorthand AJAX methods that already contain the settings we require. Some developers like to write out the full AJAX settings, mainly because they require more options than many shorthand methods provide (such as beforeSubmit()). Also, note that you can use the Firebug NET.panel to analyze HTTP requests for testing, monitoring and debugging AJAX calls.

Demo: Use $.ajax() to load content without reloading the entire page.

For this demo, HTML content is held in separate files, which are inserted below using AJAX. Showing a loading icon while an AJAX request is processing is courteous. The third content block below has a two-second delay to simulate the loading icon.

Content will appear here.

Launch Demo

We can also use functions such as $.parseJSON() and JSON.parse() from ECMAScript5, which simplifies JSON parsing. If you’re interested in JSON parsing and tree recursion, see the “Online JSON Tree Viewer Tool.”

.load()

The .load() 12 function is an AJAX shorthand method for inserting HTML straight into a matched element on the Web page.

Demo: Use .load() to grab HTML content from another Web page.

JSONP

AJAX requests are subject to the same origin policy, which means you may only send requests to the same domain. Fortunately, $.ajax() has a property named JSONP (i.e. JSON with padding), which allows a page to request data from a server on a different domain. It works by wrapping the target data in a JavaScript callback function. Note that the response is not parsed as JSON and may be any JavaScript expression.

Demo: Use AJAX and JSONP to load data from an external source.

This demo will load the latest pictures tagged “jQuery” from Flickr’s public feed.

The AJAX shorthand functions $.getJSON and $.getScript and more AJAX examples can be found on my blog.

jQuery And Events

Managing events using regular JavaScript is entirely possible, however, jQuery provides a much more user-friendly interface to manage Web page events. Examples of such events are clicking a hyperlink, moving the mouse over an image and even pressing a key on the keyboard; the list goes on. Here are some examples of key jQuery functions that may be used to manage events.

.bind() and .unbind()

The .bind() 13 function is very useful for adding event triggers and handlers to your DOM elements. In case you didn’t know, you can bind your DOM elements to a whole list of events, such as submit, change, mouseenter and mouseleave.

You may have also seen .click() 14 used in jQuery code. There is no functional difference between .click() and .bind('click'), but with the latter we have the benefits of being able to specify custom events and add data parameters. There is also an .unbind() 15 function to remove any events that have already been bound. As of jQuery 1.7 the .bind() function is an alias to .on() function. When you type in console: “jQuery.fn.bind.toString()” it will return: “function (a, b, c) { return this.on(a, null, b, c); }“.

Demo: Trigger an event when the user clicks on or hovers over a div.

Demo: Trigger an event when the user hovers over or double-clicks a div.

Press “Run demo” a few times in a row for some nice effects. Also, double-clicking the boxes will make them disappear!

Demo: Trigger an event when the user presses a key.

Press any key shown in the boxes below.

Note: The key difference between keydown and keypress events is that the latter captures each individual character entered, as opposed to just firing once per key press. To illustrate, this simple tool shows the keycodes for any key that you press.

.live(), .on() and .off()

The .live() 16 function is essentially the same as .bind(), but it can capture events on new elements that didn’t exist on the page when it was loaded; for example, if your Web page has loaded and then you dynamically insert an image onto it. If we used .bind() to attach an event when the mouse hovers over the image, it would not work. But if we used .live(), it would work! As of jQuery 1.7, you are advised to make use of the new .on() and .off() functions, instead of the .live() function, which has a few disadvantages to .on(). See “jQuery 1.7+ .on() vs. .live() Review” for a more detailed explanation of the differences.

Demo: Capture events on new or changed elements.

Click “Run demo” to dynamically insert more images and check that the event still fires on them.

.delegate()

The .delegate() 17 function provides a means of attaching event handlers to new elements (similar to the .live() function covered above). You might find .delegate() to be faster than .live() because the latter searches the entire document namespace for the elements as opposed to a single document. The much more important difference is that .live() is prone to break if used with traversing.

Demo: Delegate events to the child elements of a root element.

The demo area is the root element (orange border) with colored span child elements that have a hover event attached. Click “Run demo” a few times and hover with the mouse to trigger the effects.

.preventDefault()

The .preventDefault() 18 function can be applied to stop any element with a default action from firing: hyperlinks, keyboard shortcuts, form submit buttons, etc. These are probably the most common uses, and the function stops the hyperlink from going to its destination (the href). It’s very useful for stopping those default actions and running your custom JavaScript actions instead.

Demo: Prevent a hyperlink from going to its href.

.stopPropagation()

There are methods that do things similar to .preventDefault() but that behave differently. The .stopPropagation() function prevents the event from occurring on any ancestor elements. This can be used if you have an exception to the rule that you’ve specified for a container element with child elements. This function currently does not work with .live() events because it handles events once they have propagated to the top of the document.

Demo: Prevent a parent container from firing its event when its child is clicked.

Click both the link and div box area to see which event is fired.

This div does not use the .stopPropagation() function.

This div does use the .stopPropagation() function.

As you can see, when you click the top link it also fires off the div event, but the bottom link uses .stopPropagation(), which prevents the div event from firing. The div event will still fire if you click inside the div, as expected.

Launch Demo

.stopImmediatePropagation()

This function is nice for stopping all future bound events. The events will fire in the order they were bound, and when it hits the .stopImmediatePropagation() function, all further bound events are not fired.

Demo: Prevent all future bound events from firing.

Click both the link and div box area to see which event is fired.

This div does not use the .stopImmediatePropagation() function.

This div does use the .stopImmediatePropagation() function.

As you can see, when you click the links in the top div, all of the events fire off. But when you click the links in the bottom div, only the code for all of the links fires off because it calls .stopImmediatePropagation() on the event. This function also prevents the event from firing on any ancestor elements, just like the .stopPropagation() function, as seen in the example where the div click event doesn’t fire on the bottom links.

Launch Demo

Finding, Looping And Filtering Results

jQuery gives us fast access to finding anything on the page and the ability to loop through or filter results as we please. It also has powerful functions to manipulate and extend data and functionality associated with JavaScript objects. There are so many things to cover in this section, so we have narrowed them down to a few key functions.

$.each() and .each()

There are two different methods for iterating with jQuery: .each() 19 is used to iterate only over jQuery objects collections, while $.each() 20 is a general function for iterating over JavaScript objects and arrays. I am a big fan of functions such as these and JavaScript shorthand techniques that provide us with a fast alternative to basic JavaScript coding.

Demo: Use $.each() to loop through values in an array.

Output the countries of the world (stored in an array).

Demo: Use .each() to loop through DOM elements.

This demo loops through all of the h2 tags on this Web page and creates a table of contents.

You can use $.each() and .each() on a lot of different things, such as DOM elements, arrays, objects and JSON. For those of you who are keen, you could try five more jQuery .each() examples.

$.data(), .data(), $.hasData() and $.removeData()

Updates to the jQuery library (mainly since 1.4) has brought the ability to attach data of any type to DOM elements. This is a very useful alternative to storing data in JavaScript objects and other such methods. There are two versions: $.data() 21, which takes in the element as a parameter, and .data() 22, which can attach directly to matched elements.

Note that $.data() returns a data object to the caller, whereas .data() does not. There are also many utility functions, such as $.hasData() 23, $.removeData() 24, that help with data management.

Demo: Attach data to DOM elements.

The following example sets and gets a data object into the div for this demo area.


Set data | Get data | Has data? | Remove data

Data:

Launch Demo

.match(), .test() and :contains()

Together with the jQuery :contains() selector, you can use the pure JavaScript functions .match() and .test() to save time when filtering for string values. Let’s look at some examples.

Demo: Extract email addresses from inside HTML (i.e. a string).

We can use .test() to check whether any emails are present, and use .match() to extract them.

Curabitur placerat commodo augue eget congue. Aliquam id ante leo. Duis at libero magna, at dignissim odio. Aliquam aliquet suscipit mollis. Pellentesque libero tortor, elementum id mattis vel, mattis eget metus. somebody1@somewhere.com Nam convallis interdum imperdiet. Fusce at magna tellus. Sed mi ante, aliquam at accumsan ac, tristique sit amet dui. Aliquam eleifend molestie ligula. Vivamus eleifend, somebody2@somewhere.com diam id tincidunt posuere, ipsum dui elementum sapien, posuere pulvinar risus neque id turpis. Nullam volutpat cursus libero, sit amet euismod justo eleifend vitae.

Launch Demo

Demo: Use the jQuery :contains() selector to match elements with substrings.

We can use the :contains() selector to match substrings inside any of that element’s descendants (this is case sensitive).

  • Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  • Curabitur quis arcu ac justo pellentesque ullamcorper sit amet quis mi.
  • Nam a lorem quis lacus dapibus egestas et a ipsum.
  • Phasellus nec magna quis diam cursus egestas quis aliquet tortor.
  • Ut feugiat vestibulum mi, sit amet consequat orci facilisis ac.
  • Phasellus et enim ut sem dapibus hendrerit.

Search:

Launch Demo

.find()

The .find() 25 function is very useful for matching elements filtered by a selector, jQuery object or element. The .find() function can be used with the functions .children() 26 (which searches only the direct child siblings of the matched elements) and .parents() 27 (which searches the direct parent elements of the matched element).

Demo: Finde specific descendants of matched elements.

Launch Demo

.filter()

The .filter() 28 function allows us to reduce a set of matched elements based on a jQuery selector. This is useful when you want to process a group of elements and then further process specific child elements. The .filter() function can be used in a few different ways, such as to filter by a class name, function or jQuery object.

Demo: Use .filter() to match subelements.

In this example, .filter() is used to style paragraphs based on their content.

Launch Demo

.slice()

The .slice() 29 function lets us easily specify a subset of elements to perform actions on. It takes two parameters: start and end indices of subelements in a matched parent element.

Demo: Use .slice() to perform actions on a subset of elements.

.prev() and next()

The .prev() 30 and .next() 31 functions can be used to reference the immediately preceding or next element in a set of matched elements (in the DOM hierarchy). You can also add a selector to the functions that acts as a filter on the elements (shown in the demo).

Demo: Reference the previous and next elements in a list.

Launch Demo

$.extend()

The $.extend() 32 function can be used to combine two or more objects into the first object or into a completely new object.

$.extend( target, [object1,] [objectN] )

In the demo, we have a functional contact form on our website, and we want two more forms with similar functionality. Instead of copying all of the code that processes the form, we can use $.extend() to copy the functionality to our new forms, thus avoiding repetitive code. You might have noticed that the target element specified is a blank object; this is a trick that you will often see to create a new object of object1 and extend it with objectN (N representing any number of objects). So, in the example, we want to “copy” the existing functionality of forms.enquiry and simply override the email address.

Demo: Use $.extend() to change the send action on a form to different email addresses based on the form used.

This demo simulates the submission of three forms that all use the same code base.

Demo: Use $.extend() to specify custom settings for a plugin.

This demo shows how to specify the length of paragraph excerpts. The default is 150 characters.

Launch Demo

Addy Osmani’s book Learning JavaScript Design Patterns 33 gives greater insight into how to use the $.extend() function to override the default values of jQuery plugins.

.serialize() and .serializeArray()

The .serialize() 34 and .serializeArray() 35 functions can create string and array values from form fields in seconds! There are two demos here: the first outputs all of the form’s fields and their values, and the second creates a URL string with the form fields and values appended to the form action ready to be sent.

To run the demo, enter anything into the form and click the “Run demo” buttons below the form.

Demo: Create an array of all of the form’s field values

Demo: Create a URL string with all of the form’s field values

Do-It-Yourself Caching Methods With WordPress

There are different ways to make your website faster: specialized plugins to cache entire rendered HTML pages, plugins to cache all SQL queries and data objects, plugins to minimize JavaScript and CSS files and even some server-side solutions.

doityourself-cache-splash

But even if you use such plugins, using internal caching methods for objects and database results is a good development practice, so that your plugin doesn’t depend on which cache plugins the end user has. Your plugin needs to be fast on its own, not depending on other plugins to do the dirty work. And if you think you need to write your own cache handling code, you are wrong. WordPress comes with everything you need to quickly implement varying degrees of data caching. Just identify the parts of your code to benefit from optimization, and choose a type of caching.

WordPress implements two different caching methods:

  1. Non-persistent The data remains in the cache during the loading of the page. (WordPress uses this to cache most database query results.)
  2. Persistent This depends on the database to work, and cached data can auto-expire after some time. (WordPress uses this to cache RSS feeds, update checks, etc.)

Non-Persistent Cache

When you use functions such as get_posts() or get_post_meta(), WordPress first checks to see whether the data you require is cached. If it is, then you will get data from the cache; if not, then a database query is run to get the data. Once the data is retrieved, it is also cached. A non-persistent cache is recommended for database results that might be reused during the creation of a page.

The code for WordPress’ internal non-persistent cache is located in the cache.php file in the wp-includes directory, and it is handled by the WP_Object_Cache class. We need to use two basic functions: wp_cache_set() and wp_cache_get(), along with the additional functions wp_cache_add(), wp_cache_replace(), wp_cache_flush() and wp_cache_delete(). Cached storage is organized into groups, and each entry needs its own unique key. To avoid mixing with WordPress’ default data, using your own unique group names is best.

Example

For this example, we will a create function named d4p_get_all_post_meta(), which will retrieve all meta data associated with a post. This first version doesn’t involve caching.

function d4p_get_all_post_meta($post_id) {
    global $wpdb;

    $data = array();
    $raw = $wpdb->get_results( "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = $post_id", ARRAY_A );

    foreach ( $raw as $row ) {
        $data[$row['meta_key']][] = $row['meta_value'];
    }

    return $data;
}
Every time you call this function for the same post ID, an SQL query will be executed. Here is the modified function that uses WordPress’ non-persistent cache:
function d4p_get_all_post_meta($post_id) {
    global $wpdb;

    if ( ! $data = wp_cache_get( $post_id, 'd4p_post_meta' ) ) {
        $data = array();
        $raw = $wpdb->get_results( "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = $post_id", ARRAY_A );

        foreach ( $raw as $row ) {
            $data[$row['meta_key']][] = $row['meta_value'];
        }

        wp_cache_add( $post_id, $data, 'd4p_post_meta' );
    }

    return $data;
}

Here, we are using a cache group named d4p_post_meta, and post_id is the key. With this function, we first check to see whether we need any data from the cache (line 4). If not, we run the normal code to get the data and then add it to the cache in line 13. So, if you call this function more than once, only the first one will run SQL queries; all other calls will get data from the cache. We are using the wp_cache_add function here, so if the key-group combination already exists in the store, it will not be replaced. Compare this with wp_cache_set, which will always overwrite an existing value without checking.

As you can see, we’ve made just a small change to the existing code but potentially saved a lot of repeated database calls during the page’s loading.

Important Notes

  1. Non-persistent cache is available only during the loading of the current page; once the next page loads, it will be blank once again.
  2. The storage size is limited by the total available memory for PHP on the server. Do not store large data sets, or you might end up with an “Out of memory” message.
  3. Using this type of cache makes sense only for operations repeated more than once in the creation of a page.
  4. It works with WordPress since version 2.0.

Database-Driven Temporarily Persistent Cache

This type of cache relies on a feature built into WordPress called the Transient API. Transients are stored in the database (similar to most WordPress settings, in the wp_options table). Transients need two records in the database: one to store the expiration time and one to store the data. When cached data is requested, WordPress checks the timestamp and does one of two things. If the expiration time has passed, WordPress removes the data and returns false as a result. If the data has not expired, another query is run to retrieve it. The good thing about this method is that the cache persists even after the page has loaded, and it can be used for other pages for as long as the transient’s expiration time has not passed.

If your database queries are complex and/or produce results that might not change often, then storing them in the transient cache is a good idea. This is an excellent solution for most widgets, menus and other page elements.

Example

Let’s say we wanted an SQL query to retrieve 20 posts from the previous month, along with some basic author data such as name, email address and URL. But we want posts from only the top 10 authors (sorted by their total number of posts in that month). The results will be displayed in a widget.

When tested on my local machine, this SQL query took 0.1710 seconds to run. If we had 1000 page views per day, this one query would take 171 seconds every 24 hours, or 5130 seconds per month. Relatively speaking, that is not much time, but we could do much better by using the transient cache to store these results with an expiration time of 30 days. Because the results of this query will not change during the month, the transient cache is a great way to optimize resources.

Returning to my local machine, the improved SQL query to get data from the transient cache is now only 0.0006 seconds, or 18 seconds per month. The advantage of this method is obvious in this case: we’ve saved 85 minutes each month with this one widget. Not bad at all. There are cases in which you could save much, much more (such as with very complex menus). More complex SQL queries or operations would further optimize resources.

Let’s look at the actual code, both before and after implementing the transient cache. Below is the normal function to get the data. In this example, the SQL query is empty (because it is long and would take too much space here), but the entire widget is linked to at the end of this article.

function d4p_get_query_results() {
    global $wpdb;

    $data = $wpdb->get_results(' // SQL query // ');

    return $data;
}

And here is the function using the transient cache, with a few extra lines to check whether the data is cached.

function d4p_get_query_results() {
    global $wpdb;

    $data = get_transient('my_transient_key');

    if ($data === false) {
        $data = $wpdb->get_results(' // SQL query // ');
        set_transient('my_transient_key', $data, 3600 * 24);
    }

    return $data;
}

The function get_transient (or get_site_transient for a network) needs a name for the transient record key. If the key is not found or the record has expired, then the function will return false. To add a new transient cache record, you will need the record key, the object with the data and the expiration time (in seconds), and you will need to use the set_transient function (or set_site_transient for a network).

If your data changes, you can remove it from the cache. You will need the record key and the delete_transient function (or delete_site_transient for a network). In this example, if the post in the cache is deleted or changed in some way, you could delete the cache record with this:

delete_transient('my_transient_key');

Important Notes

  1. The theoretical maximum size of data you can store in this way is 4 GB. But usually you would keep much smaller amounts of data in transient (up to couple of MB).
  2. Use this method only for data (or operations) that do not change often, and set the expiration time to match the cycle of data changes.
  3. In effect, you are using it to render results that are generated through a series of database queries and storing the resulting HTML in the cache.
  4. The name of the transient record may not be longer than 45 characters, or 40 characters for “site transients” (used with multi-sites to store data at the network level).
  5. It works with WordPress since version 3.0.

Widget Example: Using Both Types Of Cache

Based on our SQL query, we can create a widget that relies on both caching methods. These are two approaches to the problem, and the two widgets will produce essentially the same output, but using different methods for data retrieval and results caching. As the administrator, you can set a title for the widget and the number of days to keep the results in the cache.

Both versions are simple and can be improved further (such as by selecting the post’s type or by formatting the output), but for this article they are enough.

Raw Widget

The “raw” widget version stores an object with the SQL query results in the transient cache. In this case, the SQL query would return all columns from the wp_posts table and some columns from the wp_users table, along with information about the authors. Every time the widget loads, each post from our results set would get stored in the non-persistent cache object in the standard posts group, which is the same one used to store posts for normal WordPress operations. Because of this, functions such as get_permalink() can use the cached object to generate a URL to post. Information about the authors from the wp_users table is used to generate the URL for the archive of authors’ posts.

This widget is located in the method_raw.php file in the d4p_sa_method_raw class. The function get_data() is the most important part of the widget. It attempts to get data from the transient cache (on line 52). If that fails, get_data_real() is called to run the SQL query and return the data. This data is now saved into the transient cache (line 56). After we have the data, we store each post from the set into the non-persistent cache. The render function is simple; it displays the results as an unordered list.

Rendered Widget

The previous method works well, but it could have one problem. What if your permalink depends on categories (or other taxonomies) or you are running a query for a post type in a hierarchy? If that is the case, then generating a permalink for each post would require additional SQL queries. For example, to display 20 posts, you might need another 20 or more SQL queries. To fix the problem, we’ll change how we get the data and what is stored in the transient cache.

The second widget is located in the method_rendered.php file in the d4p_sa_method_rendered class. Within, the names of class methods are the same, so you can easily see now the difference between the two widgets. In this case, the transient cache is used in the render() method. We’re checking for cached data, and if that fails we use get_data() to get the data set and generate a rendered list of results. Now, we are caching the rendered HTML output! No matter how many extra SQL queries are needed to generate the HTML (for permalinks or whatever else you might need in the widget), they are run only once, and the complete HTML is cached. Until the cache expires, we are always displaying HTML rendered without the need for any additional SQL queries or processing.

Source: http://wp.smashingmagazine.com/2012/06/26/diy-caching-methods-wordpress/

Best Slider Plugins for WordPress in 2012

Slider (Slideshow/Content Slider) plugins for WordPress are always in demand, and there are also quite a few to choose from. We’ve already done a review of content slider plugins last year, and here we are again to update the list with what we believe are the very best WordPress slideshow plugins in 2012.

This time, we’re only reviewing slider plugins which have a management WordPress interface. There are so many plugins to choose from that we had to narrow it down to those which are most user-friendly and will ultimately help you get the job done faster.

uBillboard

uBillboard is a Premium Slider plugin for WordPress. It is a jQuery based slider with a multitude of transitions and options for you to be able to customize it to your needs while not overwhelming you with options you never wanted or needed. Version 3 is a revolutionary release with most of the codebase rewritten from scratch.

Get uBillboard

Nivo Slider for WordPress

The official Nivo Slider WordPress Plugin allows you to combine the beauty and elegance of the Nivo Slider with the robust and familiar content management of WordPress. Without touching any code you can create multiple sliders that can be included anywhere and customized using the familiar WordPress backend.

&lt;a href=”http://www.vimeo.com/25230659″&gt;http://www.vimeo.com/25230659&lt;/a&gt;

Get Nivo Slider for WordPress

Sugar Slider

Sugar Slider makes it as easy as it could possibly be to create gorgeous sliders in WordPress powered site. Forget nasty custom fields and image URLs. You can even forget about manually resizing every image before you upload it.

With a huge list of features, Sugar Slider is easily the most advanced and powerful slider manager for WordPress.

With Sugar Slider you can create an unlimited number of sliders with customized settings for each one, and place them anywhere on your WordPress website with ease.

Get Sugar Slider

Estro jQuery Ken Burns Slideshow

This WordPress slider plugin includes a smooth and powerful Ken Burns effect which is completely configurable and compatible with all major browsers (including ie7 to ie9, Firefox Chrome, Opera, Safari) and mobile platforms like iphone / ipad. If the Ken Burns effect is not your thing, that’s OK because the “Estro” slider also includes a 2-way “Swipe” mode with configurable transitions.

Get Estro Slider

Riva Slider

Create and display slideshows within minutes. No commotion and designed for ease of use, saving you tonnes of time to spend on things that matter. Intelligently constructed styling panels allows you to completely customize each slideshow, unlike any other plugin of this kind. Purchasing the Riva Slider Pro also includes premium support & help documentation, if you ever run into trouble. Riva Slider really is the complete WordPress slideshow package.

Get Riva Slider

DDSlider

DDSlider introduces a new easy-to-go WordPress slider plugin with 9 different unique transitions (+fading & random—11 total) that support Inline Content. You can also have multiple sliders in the same page.

Get DDSlider

LayerSliderWP

This is the WordPress plugin of LayerSlider. You can create as many layers and sublayers as you want. You can use unlimited images with links. The script is very user-friendly, you can add global settings or local (per slide) settings to each layer or sublayer. You can change delay times, easing types, durations and much more.

Get LayerSliderWP

SliderPro

Slider PRO is one of the most powerful slider plugins for WordPress on the market. The slider offers you 100+ customizable properties, 100+ possible transition effects, 10+ skins and much more. Also, the slider’s administration area is very powerful and uses the default WordPress design, which WordPress users are already familiar with. This slider plugin is carefully coded, using WordPress development best practices, to avoid conflicts with other themes and plugins that are well coded. Please take a look at the list of features below and visit the slider’s dedicated website, sliderpro.net, for more information, screencasts and examples.

Get SliderPro

WordPress Ken Burns Slideshow

WordPress Ken Burns Slideshow is a smooth and beautiful flash slider made just for WordPress!
Based on the best selling Xml Ken Burns Slideshow, it has a lot of cool features and effects, so this slider can become the perfect way to showcase your products.

Get it today and start impressing your clients!

Get WordPress Ken Burns Slideshow

Royal Slider

RoyalSlider for WordPress is a cross-device jQuery content slider with touch-based navigation and a fluid layout. It has an amazing user-friendly admin area where you can manage slides, change slider settings, customize interface and add blocks-captions using a custom WYSIWIG editor. It has been tested for use on multiple devices including Macs, PCs, iPads, iPhones, Android devices and Blackberrys. It’s even been tested on the Amazon Kindle. Definitely one of the best sliders you can get your hands on.

Get Royal Slider

O’Slider

The o’Slider plug-in has a lot of features of a regular slider. Some of them are auto play, stop on hover, show/hide navigation, bullets list or thumbnails for a navigation, captions and in-line content. But the main cause for creation of the plug-in was to give websites’ users amazing live-background experience, which is something unique amongst the sliders we reviewed. You can use as many background layers as you want and the effect truly is original and very effective.

Get O’Slider

Source: http://www.wpmayor.com/plugin-reviews/best-slider-plugins-for-wordpress-in-2012/

 

Freelancer, Contractor & Trainer