• Feed RSS
Showing posts with label WordPress Plugins. Show all posts
Showing posts with label WordPress Plugins. Show all posts

How to Include JavaScript and CSS in Your WordPress Themes and Plugins

"Knowing the proper way to include JavaScript and CSS files in your WordPress themes and plugins is very important for designers and developers. If you don’t adhere to best practices, you run the risk of conflicting with other themes and plugins, and potentially creating problems that could have been easily avoided. This article is intended as a reference for playing nicely with others.


Best Practices Make Everyone Happy

If you’ve ever developed a theme or plugin for WordPress, or worked with one that someone else has created, you’ve probably come across several different methods for including JavaScript and CSS. While there are several methods that may appear to work in a specific set of circumstances, there is one primary method recommended in the WordPress Codex. This preferred way will ensure your theme or plugin works in all cases, assuming others also code the correct way.
There’s also some misunderstanding about what exactly the Codex says about this, which I will help clarify.

What’s in the Box?

When you download WordPress, a selection of common JavaScript libraries are already included that you can use for your JavaScript development. A list of included libraries can be found in the WordPress Codex wp_enqueue_script article.
All those libraries are included, but by default WordPress only loads the ones it needs to, and only when it needs them in the admin. If you write JavaScript that utilises one of these libraries, you need to tell WordPress that your script needs the library loaded first.

Telling WordPress About Your Script and What It Needs

Some of the things to think about when you’re coding JavaScript for WordPress are:
  • Is there an included library I can use?
  • Can I use the version that’s included?
  • Do I need to load my script in the front-end and in the admin?
  • Which front-end and admin pages do I need to load my script on?
Answering these questions helps you know what you need to do to register and load your script. This is done using a WordPress function called wp_register_script, and here is its usage according to the WordPress Codex:
wp_register_script( $handle, $src, $deps, $ver, $in_footer );
So what are these variables and do we need them every time? (This is covered on the Codex page, so I’ll be brief and use plain English)
  • $handle – what you’ll use to refer to this particular script wherever you might need to enqueue it, and you have to include this variable at the very least
  • $src – the path to the source file within your plugin or theme
  • $deps – an array containing the $handle for any other scripts your script needs to run (i.e. a dependency)
  • $ver – the version number for your script, which can be used for cache-busting. By default, WordPress will use its own version number as the version number for your script
  • $in_footer – do you want your script to load in the footer? Set this to true or false. It is false by default, so it loads in the header where wp_head() is, and if you specify true it will load where wp_footer() appears in the theme

What Is “Cache-Busting”?

Browsers remember what scripts and stylesheets they’ve downloaded for a particular site based on the URL of the script and stylesheet. If you change the URL, even just by adding a querystring, the browser assumes it’s a new file and downloads it.

Ok, So Let’s Try Some Examples

Here is the most basic example for loading a custom script:
function wptuts_scripts_basic()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' );
First, we register the script, so WordPress knows what we’re talking about. The way to find the path for our JavaScript file is different whether we’re coding a plugin or a theme, so I’ve included examples of both above. Then we queue it up to be added into the HTML for the page when it’s generated, by default in the <head> where the wp_head() is in the theme.
The output we get from that basic example is:
<script type="text/javascript" src="http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1"></script>
Now if your script relies on one of the libraries included with WordPress, like jQuery, you can make a very simple change to the code:
function wptuts_scripts_with_jquery()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_jquery' );
Note: By default, jQuery is loaded with noConflict to prevent clashes with other libraries (such as Prototype). See the noConflict section of the Codex if you don’t know how to deal with that.
See what I did there? You just add an array with the ‘jquery’ handle as a dependency. It uses an array here, because your script could have multiple dependencies. If your script uses jQuery and jQuery UI, you’d add jQuery UI to your dependency array, like array( 'jquery', 'jquery-ui-core' )
So now the output has changed, and we can see that jQuery has also been added into the <head> of the page:
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1'></script>
Let’s try an example with all the bells and whistles:
function wptuts_scripts_with_the_lot()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery', 'jquery-ui-core' ), '20120208', true );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_the_lot' );
Ok, so I’ve now added a version and specified that this script needs to be loaded in the footer. For the version number, I’ve chosen to use today’s date because it’s easy to keep track of, but you can use any version numbering you like. The output for this one is slightly different too, jQuery is output in the <head> and our script along with jQuery UI is output just before </body>, like this:
<head>
...
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
...
</head>
<body>
...
<script type='text/javascript' src='http://yourdomain.com/wp-includes/js/jquery/ui/jquery.ui.core.min.js?ver=1.8.16'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=20120208'></script>
</body>

Getting Your Priorities Straight

Some people may prefer not to use the proper enqueuing methods because they feel they have less control over the order in which scripts are loaded. For example, in a theme that uses modernizr, the theme author might want to make sure modernizr is loaded early on.
Something I haven’t mentioned earlier is more detail on how the add_action function works, as this is where we can exercise a little influence over the order of things. Here’s the usage of the function according to the WordPress Codex page:
add_action( $tag, $function_to_add, $priority, $accepted_args );
Note that often, and up until now in this article, only the $tag and $function_to_add parameters are used. The $priority parameter defaults to 10, and the $accepted_args parameter defaults to 1. If we want our scripts or styles to be enqueued earlier, we simply lower the value for $priority from the default. For example:
function wptuts_scripts_important()
{
 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js' );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_important', 5 );
The output will be the same as we’ve seen previously, but it will occur earlier in the HTML document.

Overriding Default Libraries and Using Content Delivery Networks

There may be times when you want to use a different version of a library that’s included with WordPress. Perhaps you want to use a cutting-edge version or you don’t want to wait for the next release of WordPress before using the latest stable version of jQuery. Another reason might be that you want to take advantage of Google’s CDN version of a library.
It’s important to note that this should only be done on plugins or themes used on sites that you will be personally maintaining. Any plugins or themes that you release for public use should use the libraries included with WordPress.
“Why?!”, I hear you ask. For the simple reason that you don’t control those sites. You don’t know what other plugins and themes might be used there, and you don’t know how often they will update your plugin or theme. Using the libraries packaged with WordPress is the safest option.
Having said that, if you are wanting to do this on a site you control, here’s how it’s done:
function wptuts_scripts_load_cdn()
{
 // Deregister the included library
 wp_deregister_script( 'jquery' );

 // Register the library again from Google's CDN
 wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false );

 // Register the script like this for a plugin:
 wp_register_script( 'custom-script', plugins_url( '/js/custom-script.js', __FILE__ ), array( 'jquery' ) );
 // or
 // Register the script like this for a theme:
 wp_register_script( 'custom-script', get_template_directory_uri() . '/js/custom-script.js', array( 'jquery' ) );

 // For either a plugin or a theme, you can then enqueue the script:
 wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_load_cdn' );
So first of all, I deregister the included version of the library, otherwise conflicts between different versions could be introduced. Then register the alternate version, using the same handle, and I’ve chosen to specify null as the version (it’s already in the URL!) and specified not in the footer. The rest of our code is the same, because we were depending on whatever script used the ‘jquery’ handle. The output we get now looks like:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript' src='http://yourdomain.com/wp-content/plugins/yourplugin/js/custom-script.js?ver=3.3.1'></script>
Note: One of the reasons this is a bad idea to do in a plugin or theme for public release, is that all other plugins and themes used on this site will now have to use this version of jQuery. Also, the newly registered version of jQuery doesn’t have noConflict set, so if any other plugin or theme scripts use Prototype for example, this will break things.

Don’t Be Greedy

So far we haven’t mentioned anything about how to do all this in the admin, only on the front-end. The primary difference is what action to use. Instead of add_action( 'wp_enqueue_scripts', 'wptuts_scripts_basic' ); which we use for the front-end, the action for the admin is add_action( 'admin_enqueue_scripts', 'wptuts_scripts_basic' );
Something that’s important to do for both the front-end and admin is be selective about which pages you load your scripts on. If your plugin or theme has a script that only does something on one front-end or admin page, such as the theme’s options page, or maybe a page with a specific widget, you only need to load your script on that page. No point clogging things up and loading scripts on pages where they’re not being used!
There’s a great example in the WordPress Codex on how to load scripts only on plugin pages. Because plugins and themes can vary a lot in how they’re written, I won’t go into specifics here on how to be choosy about which pages you load scripts on, but it was important to mention so you’re aware of it when you’re coding.

That’s Scripts, Now Styles

The process for styles is almost exactly the same as the process for scripts. It is done using a WordPress function called wp_register_style, and here is its usage according to the WordPress Codex:
wp_register_style( $handle, $src, $deps, $ver, $media );
Note that the only difference there between wp_register_script and wp_register_style is that instead of an $in_footer parameter, we have a $media parameter. This parameter can be set to any of the following: 'all', 'screen', 'handheld', and 'print', or any other W3C recognised media type.
So an example of how you might enqueue a style would be:
function wptuts_styles_with_the_lot()
{
 // Register the style like this for a plugin:
 wp_register_style( 'custom-style', plugins_url( '/css/custom-style.css', __FILE__ ), array(), '20120208', 'all' );
 // or
 // Register the style like this for a theme:
 wp_register_style( 'custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), '20120208', 'all' );

 // For either a plugin or a theme, you can then enqueue the style:
 wp_enqueue_style( 'custom-style' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_styles_with_the_lot' );
This is a fairly comprehensive example, utilising most of the parameters, and the output it produces looks like:
<link rel='stylesheet' id='custom-style-css'  href='http://yourdomain.com/wp-content/plugins/yourplugin/css/custom-style.css?ver=20120208' type='text/css' media='all' />

So, Why Doesn’t Everyone Already Do Things This Way?

Good question, and the other question I guess you might ask is, “What makes you think this is the ‘right’ way and not just your preference?”. Essentially the answer is that this is the approach recommended by WordPress. It ensures that any combination of plugins and themes should be able to work together happily and without doubling up.
I’ve seen a few themes and frameworks around the place that use <script></script> and <link /> tags in their header.php, and even footer.php, files to load the scripts and styles for the theme itself. There’s really no reason to do things this way. As I’ve demonstrated above, it’s perfectly possible to prioritise scripts and styles and nominate whether they load in the header or footer from the comfort and safety of your functions.php. The benefit being that your theme / framework will work with a wider range of other plugins / child themes.
One example was loading jQuery using the <script></script> tags, which might appear to work nicely, but this can actually cause jQuery to be loaded twice! Loading jQuery in this way will not stop WordPress from loading its version of jQuery for other plugins, as WordPress’ version is in noConflict mode by default, and a plugin may specify it as a dependancy. So now you’ll have jQuery working for both noConflict mode and $, and also probably break any plugin that uses the Prototype library.

Conclusion

WordPress is a fantastic system, and it has been developed with a lot of thought. If there’s a mechanism made available to do something, it’s often a good idea to use it. When developing your plugins and themes, try to remember to code thoughtfully and for playing nicely with others.
What do you think about the use of wp_enqueue_script and its associated functions and actions? Do you know of any examples where it’s being done incorrectly? Do you know of any reason not to follow the advice above?"
read more

How to Build an E-Commerce Website Using WordPress: Part 2

"This is the second and final part of the WordPress E-Commerce tutorial. Here we will go through the final steps of completing our WordPress e-commerce web site. You will be shown with the process of adding products to your site, using different widgets to enhance your site, using different reports to keep track of the sales and efficient use of shortcodes.

Once done with the wp-ecommerce settings, adding your products and selling becomes child’s play.

Before We Move On

Before we dive straight into the process, let’s look at a few changes we made to the e-commerce site since part 1.
1. We have installed the latest version of Liquorice theme, i.e Liquorice 2.2 by Nudge Design.
2. We have updated WordPress to the latest WordPress 3.3 version.
3. Under Settings -> Store -> Shipping we have edited the Flat Rate option and put $ 0.00 under all the fields. This is done since we will use different shipping rates for different products (without any base rates). Putting $ 0.00 keeps this feature enabled. If you want to keep a Base rate to be added to the individual shipping cost of each product, you may enter your Base rates here.
Now our site looks like….

Adding Products

Lets discuss a few useful options before we add our first product.
1. The Product -> Coupons page lets us add special discount coupons for the products. Here you can specify the Coupon Code, Discount, Coupon Expiry Date and other conditions as per your requirements.
2. The Product -> Variations options lets you add variations to your products.
Supose you are selling T-Shirts and you want to specify its variations in Size or Color. This options lets you define your Variations Set first and then define the different variations under it. You can also set a price for each of the variations.
3. The Product -> Product Tags options lets you define your own product tags useful for searching a product while using the Product Tags widget.

Adding Product Categories

Before adding a product lets add our product categories from the Products -> Categories page.
While adding a category you need to specify the Name, Parent Category (if any) and Description. You may specify a Thumbnail image and also restrict a few countries from accessing this product. As of now we have added three categories- Flowers, Confectioneries and Chocolates.

Adding Your First Product

The Products -> Add New option lets you add products to your e-commerce site.
Here you need to specify the Product Name, Product Description, Product Tags and categorize your product under the created Categories. The Variations option lets you add your created Variations to this product.
Now you need to add the Price, Stock and Taxes(if any) of this product. While adding the Price, you can also specify a Sale Price to show a discounted price to your customers, which will increase the customer’s interest.
The Product Download option is used if you are selling downloadable products.
Please upload Product image by clicking the Manage Products Images link. Here you have the option to upload the image form your local hard disk, URL or using your WordPress Media Library. You can also Drag and Drop your images in this page.
The most important part is specifying your shipping options. Here at first you need to specify a Weight for your product and then specify the Local and International Shipping Charges. You also have the option to disregard the shipping charges.
After making all the changes click on Publish.
Now your product appears under the Products -> Products option. You can edit/delete the product from here.
Lets add two more products to our site.
Lightbox effect Image of products.
In the same way you can add different products to your site. You can also use the Settings -> Store -> Import option to upload products in a batch using a comma delimited text file.. After adding the products you can upload the images and insert the additional details.

Using a Few Essential Widgets

Under the Appearance -> Widgets, you will find many useful widgets. You just need to drag and drop it in the area of the page where you want to place it. Lets discuss a few of these one by one.
1. Latest Products– Using the Latest Products widget will display the recently added products on your sidebar or the area where you are placing this widget.
2. Products Categories – Using this widget will show all your product categories in your sidebar. The customer can search for products using those categories.
3. Product Specials – This widget displays those products that is on Sale in your site, i.e if the product has any discounted price or the Table Rate Price.
4. Product Tags- This widget displays the specified product tags in your sidebar so that customer can search for their required products using those Tags.
5. Price Range – This widget adds the price range of the products in your sidebar through which the customer can search for the products using different price ranges.
6. Shopping Cart – If you have selected the Widget option for your Cart Location , you can use this widget to display the shopping cart in your sidebar.
7. Text- This wizard is very helpful if you want to display any special ad on your website. You can also copy paste html snippets in this widget.

Reporting

Once the products have been purchased, you can see the purchase reports under the Sales Summary, Sales by Quarter and Sales by Month. Under the Sales Summary you will get to know the current month’s sales as well as the Total Income. The Sales by Quarter displays the sales by Financial Quarters and Sales by Month displays Last four months of sales on a per product basis.
Under Dashboard -> Store Sales, you will get a summary of the sales for the Current Month. It is through this screen that you will be able to see all the sales details and also process the orders. You can change the Sales Status and also add anew Tracking IDs to each of the products. Clicking on the Details->Items displays the invoice. You can also email the customer the purchase receipt from this page.
That’s it your e-commerce site is ready for the first sale.While checking out, the system automatically asks for you Login Credentials or Registers you if you are a new customer.

Importance of Shortcodes

Introduction
A shortcode is a specific code in WordPress that lets you do great things using very little effort. The other name of Shortcode is Shortcut, you can embed files or create objects using just one line of shortcode which otherwise would have required lots of ugly codes.
Here are the details of a few important shortcodes used in our site.
productspage shortcode helps in displaying the complete list of products and their presentation in the website. This is a very important shortcode in Wp e-commercerce that is used within Products Pages, Products Categories and single Product Templates.
shoppingcart shortcode displays the checkout page or the checkout template in the site.
transactionresults shortcode displays the transaction page which shows the customers the status and the summary of their purchase.
userlog shortcode displays the My Account page of the site. Its is used by already registered customers to see their details regarding purchase history, downloads and account details.
Some other examples of shortcodes-
[wpsc_products product_id='288'] – Displays the product which has ID of 288 [buy_now_button product_id='198'] – Displays a PayPal buy now button for the product(ID-198). [add_to_cart=112] – Displays an add to cart button for the product(ID-112).

Conclusion

I hope you have enjoyed both the e-commerce tutorials.This is only the tip of the iceberg of what can be done with the Wp e-commerce plugin. In the future I shall try to bring more tutorials on WordPress e-commerce."
read more

How to Build an E-Commerce Website Using WordPress: Part 1

"Today we will be creating a simple but powerful e-commerce site using one of the most popular WordPress plugins called WP e-Commerce. Using this plugin we will be creating a website which sells holiday gifts!


Knowing WP e-Commerce Plugin

WP e-Commerce is a powerful shopping cart plugin for WordPress developed by GetShopped.org. Using this plugin in WordPress lets users buy your products and services online. Given below are some of the features of this amazing plugin.
  • Easy to install.
  • Works with any WordPress theme.
  • Supports all kind of WordPress Widgets.
  • Template modification is very easy.
  • Instant support community.
  • All the popular payment gateways supported.
  • 100% Search Engine friendly.
  • Can be used to promote products on social networking sites.
  • Supports multiple languages.
  • Can be integrated with Google.
  • Supports multiple currencies.
  • Multi shipping options.
  • SSL security integration and many more.
You can start selling your products, downloads and services right away.
There are also additional features for premium customers. You can go through all of these features by clicking here.

Prerequisites of installing WP e-Commerce

Before installing and activating the plugin lets discuss some core pre requirements.
1. WordPress development environment must be ready in your system.You can either host your site locally or using a web hosting service. You can also use BitNami for WordPress, which is a great combined tool for WordPress development and testing.
2. Please log in to your WordPress admin and go to Post -> All Posts and remove (trash) the default post from the list.
3. Please go to Posts -> Categories and create categories relevant to your products. Here we will create Bakery Items, Confectionaries and Flowers. While creating the categories you just need to provide the name and a short description.We have changed the Uncategorized category to Bakery Items.
4. Please go to Pages -> All Pages and remove (trash) the default page from there.
5. You can customize and keep the current theme or go to Appearance -> Themes to install a new one that suits your e-commerce site. You can also use third party themes for your e-commerce site.
6. On the Appearance menu click on Header and upload your site’s header image. You may need to crop the image while uploading.
7. Under the Settings -> General change the following things.
  • Site Title to Christmas Shopping
  • Tagline to Gift n Enjoy
  • Select the Anyone can Register option.
Please click on Save Changes after changing these options.
8. Please go to Settings-> Permalinks. Select Custom Structure and enter /%postname%/. Finally Save the changes done. Permalinks helps you to create customized urls for your pages instead of the default ones.
9. In the Settings -> Discussions page, uncheck all the options and click Save Changes. This will prevent any type of comment in your e-commerce site.

Installing WP-eCommerce

This plugin can be installed either manually or from the WordPress plugin menu.
Lets install it using the easiest method that is by using the WordPress plugin menu.
Please go to Plugins -> Add New and Search for WP e-commerce. In the list generated locate the WP e-commerce plugin and click on Install Now.
After the plugin is installed, click on Activate Plugin to activate the plugin.
That’s it the plug has been installed and ready to use.
After the plugin is installed, you will see a Products menu in your dashboard and a Store option under Settings. The Products menu is used for adding different products to your site and the Store option is used for the plugin settings.
In your dashboard you will also find three new items which shows- Sales by Quarter, Sales by Month and Sales Summary.

A few more additional changes before configuring the plugin

Please go to Settings -> Reading and under Front page displays select A static page and choose the Products Page as your front page. This will ensure that when customers visits your site, the products page will be displayed by default.

Defining a Contact Us page for your site.

We shall use the Contact Form 7 plugin to create a Contact Us page for the site.
For this please go to Plugins -> Installed Plugins and Activate the Contact Form 7 plugin. After activation please click on the plugin settings.
In the plugin’s settings page you can create a customized contact us form by using different types of options available there. Under the Mail option enter your email address beside the To: field. Under Messages you can use your own error messages. Finally copy the generated short code and paste it into your post, page or text widget content. In our case we have copied the code [contact-form-7 id="18" title="Contact form 1"] to a newly created page named Contact Us.
Finally our site looks…

Lets set up the WP-eCommerce plugin before adding products

Please go to Settings -> Store. Here you can set the different options for the plugin.

1. General

a) Select a Base Country/ Region.
b) Select the markets you are selling products to.
c) Set the amount of time the items in a customer's cart are kept reserved.
d) Select a Currency Type and Currency Sign Location.
Finally click Update.

2. Presentation

a) Select Add to Cart under Button Type.
b)You can enable additional options from Show Product Ratings, Show Stock Availability, Display Fancy Purchase Notifications, Display per item shipping etc. For now we will only enable the Display per item shipping: option.
c) Under Gird View Settings we will enter 3 products per row and select Display Description, Display "Add to Cart" Button and Display "More Details" Button options.
d) Under Shopping Cart Settings select Cart Location as Widget. and enable Display "+ Postage & Tax":
e) You can set the product image thumbnail format from the Thumbnail Settings.
f) You may enable other options as per your requirements. As of now we shall keep the other options as default.
Finally click Update.

3. Admin

a) The first three options are used for downloadable products like software, music, games etc.
b) Under Purchase Log Email and Purchase Receipt – Reply Address: enter your email address.
c) Enter your name against Purchase Receipt – Reply Name:
d) Set Terms and Conditions if any.
e) You can edit the Purchase Receipt and Admin Report formats under the Custom Messages.
f) Tracking responses can also be created from this page.
Finally click Update.

4. Taxes

Here you can define the tax rules according to your requirements. You can also define the tax per item.

5. Shipping

a) We will enable the Use Shipping option since we are selling Christmas Gifts.
b) By selecting the Enable Free Shipping Discount, you can provide shippings discounts to customers.
c) Under Shipping Modules we have selected and edited the Fixed Rate shipping option and provided the shipping rates for the customers of different countries.
d) Under External Shipping Calculators we have selected UPS as our shipping gateway and provided all the details.
Please note: You need to have a UPS account in order to use this option. You can also use other shipping options.
Finally click Update.

6. Payments

Here you can define the payment gateway for the customers. Among the various options available, we will use the Test Gateway and PayPal Payments Standard 2.0. The PayPal Payments Standard 2.0 option can be used if you have a PayPal account. This lets customers buy products using PayPal. We will also use the Test Gateway option as a means of manual payment. After selecting and editing the payment options you need to provide all the details.
Finally click Update when done.

7. Checkout

a) Under Misc Checkout Options enable Users must register before checking out, Enable Shipping Same as Billing Option: and Force users to use SSL options.
b) The Form Fields define the Customer's checkout form. You can create a new form or use the default one. You can change the field's Name, Type and Mandatory options. You can also Drag and Drop, Delete different fields based on your requirements.
Finally click Save Changes after its done.

8. Marketing

This option is used to share and broadcast your products among different social networking sites, RSS and Google Merchant Center. For now we shall select the Show Share This, Customer Survey and Facebook Like options.
Click Update when done.

9. Import

The import option is used to upload products automatically using a csv file. We shall come to this later.
In the next part of this Tutorial I shall explain how to add products and use different widgets/plugins in your e-commerce site."
read more

7 Simple Rules: WordPress Plugin Development Best Practices

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


Rule 01: Have a Strategy

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

Rule 02: Use Consistent and Clear Coding Standards

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

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

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

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

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

 }

 return $result;

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

Use Namespacing

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

 function hello_world(){

   return 'Hello World!';

 }

 function goodbye_world(){

   return 'Goodbye World!';

 }

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

echo $my_new_plugin->hello_world();

echo $my_new_plugin->goodbye_world();

Rule 03: Take Security Seriously

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

Sanitize inputs, escape outputs

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

Use Nonces for Form and URL Verification

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

 if(check_admin_referer('register_nonce')){

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

     echo 'Registration verified!';

   }

 }else{

   echo 'Registration verification FAILED!';

 }
}

Rule 04: Access Web Services Intelligently

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

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

 $body = $page_data['body'];

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

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

Rule 05: Internationalization

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

Rule 06: Load Only What You Need

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

 //load my plugin stuff for the admin pages

}else{

 //load my plugin stuff for the frontend

}

Rule 07: Tidy Up After Yourself

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

 //delete options, tables or anything else

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

Bonus Tips

Turn on debug

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

Study the WordPress function library

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

Get some peer review

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

Don’t use deprecated functions!

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

Use a good WordPress code forum

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

Take some pride in your work!

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

Top WordPress Plugins from CodeCanyon: November Edition

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


1. UberMenu

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

2. uBillboard Slider

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

3. WordPress Video Gallery

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

4. Styles with Shortcodes

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

5. Lightbox Evolution

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

6. Font Uploader

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

7. Custom Backgrounds

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

8. WordPress Email Newsletter

Easily send mass emails to your existing wordpress user database.

9. 5 Second Google Maps

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

10. Special Recent Posts

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

11. Security Ninja

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

12. Visual Composer

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

13. Foobar Notification Bars

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

14. SocialPop

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

15. Estro Slider

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

16. Premium Pricing Tables

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

17. Flip Book

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

18. jGallery

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

19. Ninety Ajax Login/Register

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

20. Slider Evolution

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