Archive for the ‘WordPress’ Category

Attaching image to post from external url wordpress

Its very simple to attach image from any external url to post by code.
Here is the simple code that will attach image to your post.

require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$upload = media_sideload_image('IMAGE_URL', "POST_ID", "IMAGE_DESC");
die ( $upload );


e-Shop Recurring Payment Plugin

Hii Friends/Webmasters,

I have seen few question over web “Can eShop handle Recurring Billing through PayPal?”. Yes ofcourse it can handle here is the solution in face of plugin :)

As i am big fan of bloging sites, i have read lots of things regarding eshop. I have seen developers/webmasters love the eshop plugin.

Here i again with one new solution for your shopping site that you require :) Guess… Hmmm… Yeah Its “e-Shop Recurring Payment”.

I have completed the first version of e-Shop Recurring payment.

First of all i would like to describe your what is “Recurring Payment”.

Recurring payments are an option that allows your customers to make Visa card payments to you automatically at regular intervals. They can be used in a variety of situations, from monthly subscriptions and leasing arrangements to paying electricity and telephone bills.

Recurring payments mean that customers do not have to worry about remembering to make their payment each time it is due, while you provide better service, receive your payments regularly and save valuable time.

How it works with e-Shop ?
You just need to download the “e-Shop Recurring Payment” Plugin from the site. Install it using installation wizard of wordpress.. That’s It.

Version Support.
It support latest stable version of e-Shop (3.2)

so if any one is in need for this feature let me know i will do it. You can reach me at or fill the contact us form with
subject of “Paypal Pro API Plugin for eShop” and your suggations on message part.

You can see the below screencasts that i will provide you for admin settings and user-end setting.
Admin Side User Interface:

e-Shop Recurring Payment Plugin

e-Shop Recurring Payment Plugin

Front Side User Interface:

eshop recurring payment plugin wordpress

eshop recurring payment plugin wordpress

Paypal Pro API Plugin for eShop

I have got lots of request for integration of eshop with paypal pro API..

Clients are asking for same solution but their wording are different….
I would like someone to modify the php for eshop’s paypal gateway so that customers do not leave my site when checking out.

I need a Paypal Pro merchant gateway plugin for eShop. eShop currently offers a standard paypal gateway but does not have settings/option for the Paypal API direct pay. I am aware other shopping carts offer this (like wp ecommerce) but I like the eShop interface and functions.

I would very much like it written as a plugin for eShop.

WordPress version: 3.0.4
eShop version: 6.0.2


Finally, I desire to add this feature to eShop wordpress plugin..
You can see the demo at my given demo url.
Demo URL :

It was great to customize this plugin as its great achievement and everyone is in need of this…..

Currenltly i have customized “eShop” plugin for developers it might be easy to integrate my customization but may be not so easy for webmaster to do this job.

so if any one is in need for this feature let me know i will do it. You can reach me at or fill the contact us form with
subject of “Paypal Pro API Plugin for eShop” and your suggations on message part.

You can see the below screencasts that i will provide you for admin settings and user-end setting.
Admin Side User Interface:

Front Side Paypal Pro checkout option:

Custom error pages with htaccess

A tutorial to enable custom error pages with an htaccess file. Note htaccess files only work on a linux server

To create an htaccess file open notepad or any plain text editor and save the file as .htaccess, if using notepad make sure the file type is set to all files or you will create a txt file.

There are five types of error pages that your server has to offer which are:

400 – Bad request

401 – Authorization Required

403 – Forbidden directory

404 – Page not found

500 – Internal Server Error

if you don’t have the right page like say a 404 page then the server issues you the error and informs you it could not find an error document. Making your own custom error page is very easy with htaccess on an htaccess file enter the command ErrorDocument then the error number then a forward slash then the path to the error page which tells the page where to go like this:

ErrorDocument 404 /errors/404.php

The final file will look like this:

ErrorDocument 400 /400.html

ErrorDocument 401 /401.html

ErrorDocument 403 /403.html

ErrorDocument 404 /404.html

ErrorDocument 500 /500.html

Save the htaccess file in the root of the server then if their is an error the custom error page is served.
Credit :

WordPress Multisite

Create A Network

In WordPress 3.0, you now have the ability to create a network of sites (Multisite). This Article is instructions for creating a network. It is very similar to creating your own personal version of

NOTE: If you are currently running a version of WordPress MU, you do not need to complete these steps. your network is already enabled. Once you upgrade to the 3.x branch, you will be prompted to update your .htaccess rules for MultiSite.

Before You Begin

Admin Requirements

If you want to run a network of blogs you should at least have a basic understanding of UNIX/Linux administration. A basic knowledge of WordPress development, PHP, HTML and CSS is recommended as well.

Setting up and running a multi-site installation is more complex than a single-site install. Reading this page should help you to decide if you really need a multi-site install, and what might be involved with creating one. If the instructions on this page make no sense to you, be sure to test things on a development site first, rather than your live site.

Server Requirements

Since this feature requires extra server setup and more technical ability, please check with your webhost and ask if they support the use of this feature. It is not recommended to try this on shared hosting.

You are given the choice between sub-domains or sub-directories in Step 4: Installing a Network. This means each additional site in your network will be created as a new virtual subdomain or subdirectory.

  • Sub-domains — like and
  • Sub-directories — like and

It is also possible later, through use of a plugin such as WordPress MU Domain Mapping, to map individual sites to independent domain names.

Sub-directory sites
It works with the use of the mod_rewrite feature on the server having the ability to read the .htaccess file, which will create the link structure.
If you are using pretty permalinks in your blog already, then subdirectory sites will work as well.
Sub-domain sites
It works using wildcard subdomains. You must have this enabled in Apache, and you must also add a wildcard subdomain to your DNS records. (See Step 2 how to set up.)
Some hosts have already set up the wildcard on the server side, which means all you need to add is the DNS record.
Some shared webhosts may not support this, so you may need to check your webhost before enabling this feature.

WordPress Settings Requirements

  • Giving WordPress its own directory will not work in WordPress 3.0 with multisite enabled. It interferes with the member blog lookup.
  • You cannot create a network in the following cases:
    • “WordPress address (URL)” is different from “Site address (URL)”.
    • “WordPress address (URL)” uses a port number other than ‘:80′, ‘:443′.
  • You cannot choose Sub-domain Install in the following cases:
    • WordPress install is in a directory (not in document root).
    • “WordPress address (URL)” is localhost.
    • “WordPress address (URL)” is IP address such as
  • You cannot choose Sub-directory Install in the following cases:
    • If your existing WordPress installation has been set up for more than a month, due to issues with existing permalinks. (This problem will be fixed in a future version. See Switching between subdomains and subfolders for more information.)

(See wp-admin/network.php for more detail)

Step 1: Backup Your WordPress

Your WordPress will be updated when creating a Network. Please backup your database and files.

Step 2: Setting Wildcard Subdomains

(If this is a Sub-directories Install, skip this step.)

Sub-domain sites work with the use of wildcard subdomains. This is a two-step process:

  1. Apache must be configured to accept wildcards.
    1. Open up the httpd.conf file or the include file containing the VHOST entry for your web account.
    2. Add this line:
      ServerAlias *
  2. In the DNS records on your server, add a wildcard subdomain that points to the main installation. It should look like:
    A *

External links:

Specific Configurations

Due to the fact that every host is configured differently, the following ‘per site’ directions are not exhaustive. In all cases, if you cannot determine how to set up wildcard subdomains, contact your webhost for directions.


Make a sub-domain named “*” (wildcard) at your CPanel (* Make sure to point this at the same folder location where your wp-config.php file is located.


There are several steps that differ when setting up the server for wildcard subdomains on a server using Plesk Panel compared to a server using cPanel (or no control panel). This article Configuring Wildcard Subdomains for multi site under Plesk Control Panel? details all the steps involved.

DirectAdmin panel

Click “User Panel” -> DNS Management -> add the following three entries using the three columns:

* A

(Replace “” with your website IP.) Click “Admin Panel” (If you have no “admin panel” ask your host to do this.) -> Custom Httpd -> -> In the text input area, just paste and “save” precisely the following:

ServerAlias *.|DOMAIN|

(If you ever need to un-do a custom Httpd: return here, delete text from input area, save.)

Step 3: Allow Multisite

To enable the Network menu item, you must first define multisite in the wp-config.php file.

Open up wp-config.php and add this line above where it says /* That's all, stop editing! Happy blogging. */:

define('WP_ALLOW_MULTISITE', true);

Step 4: Installing a Network

This will enable the Network menu item to appear in the Tools menu. Visit Administration > Tools > Network to see the screen where you will configure certain aspects of our network.

Tools Network SubPanel

Addresses of Sites in your Network
You are given the choice between sub-domains or sub-directories (if none of the above applies). This means each additional site in your network will be created as a new virtual subdomain or subdirectory. you have to pick one or the other, and you cannot change this unless you reconfigure your install. See also Before You Begin.

  • Sub-domains — like and
  • Sub-directories — like and
Network Details
There are filled in automatically.
Server Address
The Internet address of your network will be
Network Title
What would you like to call your network?
Admin E-mail Address
Your email address.

Double-check they are correct and click the Install button.

You may receive a warning about wildcard subdomains. Check Setting Wildcard Subdomains.

Warning! Wildcard DNS may not be configured correctly!

The installer attempted to contact a random hostname ( on your domain.

To use a subdomain configuration, you must have a wildcard entry in your DNS. This usually means adding a * hostname record pointing at your web server in your DNS configuration tool.

You can still use your site but any subdomain you create may not be accessible. If you know your DNS is correct, ignore this message.

Step 5: Enabling the Network

The rest of the steps are ones you must complete in order to finish.

Tools Network Created

0. First, back up your existing wp-config.php and .htaccess files.
1. Create a blogs.dir directory under /wp-content/
This directory is used to stored uploaded media for your additional sites and must be writable by the web server. They should be CHOWNed and CHMODed the same as your wp-content directory.
2. Add the extra lines your WordPress installation generates into your wp-config.php file.
These lines are dynamically generated for you based on your configuration.
Edit the wp-config.php file while you are logged in to your sites admin panel.
Paste the generated lines immediately above /* That's all, stop editing! Happy blogging. */.
3. Add the generated mod_rewrite rules to your .htaccess file, replacing other WordPress rules.
(If there isn’t one, then create it.)
These lines are dynamically generated for you based on your configuration.
4. Log in again.
Once the above steps are completed and the new wp-config.php & .htaccess files are saved, your network is enabled and configured. You will have to log in again. click “Log In” to refresh your Adminstration Panel. If you have problems logging back in, please clear your browser’s cache and cookies.

Step 6: Network Admin Settings

In 3.0, you had a new menu for Super Admin, but as of 3.1 you have an entire sub-section for Network Admin. The link can be found on the upper-right of all admin screens, by your name.

Go the Settings panel to configure network options, and the Sites panel to manage your sites.

Things You Need To Know

Here are some additional things you might need to know about advanced administration of the blog network.

User Access

By design, all users who are added to your network will have subscriber access to all sites on your network.

Also, site admins cannot install new themes or plugins. Only the Network Admin (aka Super Admin) has that ability.


While permalinks will continue to work, the main blog (i.e. the first one created) will have an extra entry of blog, making your URLs appear like

This is by design, in order to prevent collisions with SubFolder installs. Currently there is no easy way to change it, as doing so prevents WordPress from auto-detecting collisions between your main site and any subsites. This will be addressed, and customizable, in a future version of WordPress.

Also note that the blog prefix is not used for static pages which will be accessible directly under the base address, e.g. If you try to create a static page in the first blog with the name of another existing blog, the page’s permalink will get a suffix (e.g. If you create a new blog with the slug of an existing static page, the static page will not be reachable anymore. To prevent this, you can add the names of your static pages to the blacklist so that no blog with this name can be created.

WordPress Plugins

WordPress Plugins now have additional flexibility, depending upon their implementation across the network.
  • Site Specific Plugins: WordPress Plugins to be activated or deactivated by an individual blog owner are stored in the plugins directory. You need to enable the Plugins page for individual site administrators from Network > Options.
  • Network Plugins: WordPress Plugins stored in the plugins directory can be activated across the network by the super admin.
  • Must-Use Plugins: Plugins to be used by all sites on the entire network may also be installed in the mu-plugins directory as single files, or a file to include a subfolder. Any files within a folder will not be read. These files are not activated or deactivated; if they exist, they are used.

Categories and Tags

Global terms are disabled in WordPress 3.0 by default. You can use the Sitewide Tags WordPress Plugin or other similar Plugins to incorporate global tags on the portal/front page of the site or on specific pages or blogs within the network to increase navigation based upon micro-categorized content.

Switching between subdomains and subfolders

If you have had WordPress installed for longer than a month and are attempting to activate the network, you will be told to use Sub-domain sites. This is in order to ensure you don’t have conflicts between pages (i.e. ) and sites (i.e. ). If you are confident you will not have this issue, then you can change this after you finish the initial setup.

In your wp-config.php file, you’ll want to change the define call for SUBDOMAIN_INSTALL:

Use SubDomains
define( 'SUBDOMAIN_INSTALL', true );
Use SubFolders
define( 'SUBDOMAIN_INSTALL', false );

You’ll also have to change your .htaccess to the new setup. Be aware, you may have issues if you attempt this after being on one setup or the other for any length of time, so proceed with caution.

.htaccess and Mod Rewrite

Unlike Single Site WordPress, which can work with “ugly” Permalinks and thus does not need Mod Rewrite, MultiSite requires its use to format URLs for your subsites. This necessitates the use of an .htaccess file, the format of which will be slightly different if you’re using SubFolders or SubDomains. The examples below are the standard .htaccess entries for WordPress SubFolders and SubDomains, when WordPress is installed in the root folder of your website. If you have WordPress in it’s own folder, you will need to change the value for RewriteBase appropriately.

As a reminder, these are EXAMPLES and work in most, but not all, installs.

SubFolder Example

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule  ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L]
RewriteRule  ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L]
RewriteRule . index.php [L]
# END WordPress

SubDomain Example

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# uploaded files
RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule . index.php [L]
# END WordPress

WordPress Hack – How to Insert Ads in the Middle of Your Content!

With this hack you will be able to add adsense block (or somethings else) in the midde of your post after 2 paragraphs.

As a hard hack my suggestion is make a template backup before apply this tricks.

  • Open your “single.php” file (in your template folder)
  • Search
    <?php the_content(); ?>
  • Replace with:
      $content = apply_filters('the_content', $post->post_content);  //get the post content store in $content
      $save = explode("</p>", $content);  //Separate the content into <p> blocks
      $tcount=0; //this is count for number of <p> blocks
      $adon=0;  //this is a variable so you don't show ads more than once.
      foreach($save as $item) {
        echo $item;  //print the <p> block
        echo "</p>"; 
        if(preg_match('/<p> /',$item)==0 && $tcount>=1 && $adon==0) {
    Replace this with Your adsense code!!!
     if(preg_match('/<p> /',$item)==0 && $tcount>=4 && $adon==1) {
    Replace this with Your adsense code if you want additional adsense blocks for super long blog posts or leave it empty if you don't want one.

    credit goes to :

How to display post count from a category

I am just recording my work right now. I found this to work really well.

function wt_get_category_count($input = '') {
global $wpdb;
if($input == '')
$category = get_the_category();
return $category[0]->category_count;
$SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->term_taxonomy.term_id=$input";
return $wpdb->get_var($SQL);
$SQL = "SELECT $wpdb->term_taxonomy.count FROM $wpdb->terms, $wpdb->term_taxonomy WHERE $wpdb->terms.term_id=$wpdb->term_taxonomy.term_id AND $wpdb->terms.slug='$input'";
return $wpdb->get_var($SQL);

Place above in your function.php file.

And then add below inside the regular php begin and end to any location you want the count to be displayed.
echo wt_get_category_count(categoryid);

Thanks to

Sidebars in WordPress

Over the past few months, I’ve seen the code for hundreds of WordPress themes. I’ve seen some beautiful code and some downright nasty code. One thing that I’ve seen more often than not is the same few lines for handling sidebars. This is code from 2007 and most likely copy-pasted from older WordPress themes.

I just wanted to clue an extremely large portion of the theme development community in on a little secret: sidebars have been a part of WordPress core and have seen some updates over the last three years.

With that in mind, I’m going to walk you through the steps of creating and using sidebars for WordPress themes. Maybe you’ll even pick up on some things you didn’t know about. The goal is to teach theme developers how to properly register sidebars and end this cycle of using outdated code.

What are sidebars?

The term “sidebar” actually refers to two different things in WordPress:

  • Dynamic sidebar: A container for a set of widgets, which the user can set from the Widgets screen in the admin.
  • Sidebar template: A theme template that displays content.

In most situations, a theme would register a dynamic sidebar and load its widgets within a sidebar template. This isn’t always the case, but it’s generally what you’ll see. It’s important to understand that there’s a difference though.

Generally, the term “sidebar” refers to a dynamic sidebar, which is the focus of this article. However, I will touch on sidebar templates as well.

One thing I’ve been disappointed with when looking at themes is that many theme developers aren’t fully taking advantage of one of the most powerful features of WordPress. Most themes will only have a single sidebar, maybe two at most. But, these themes will create large theme options pages for things that could be easily handled with widgets or put content directly in templates. I’d love to start seeing themes with more sidebars.

Registering a dynamic sidebar

Example of a dynamic sidebar in WordPress

Themes usually fail my quality guidelines the most in this area, so if you’re a theme developer, let’s make sure you get this right. Properly registering a sidebar is the most important part of the process because what you set here will trickle down to other sidebar functions you’ll use later.

When registering a sidebar or multiple sidebars, you would do so from your theme’s functions.php file.

The code shown below is an example of how to properly register a sidebar in WordPress using the register_sidebar() function. In this particular example, you’ll register a sidebar called primary, which will be the example sidebar used throughout the remainder of this tutorial.


add_action( 'widgets_init', 'my_register_sidebars' );

function my_register_sidebars() {

	/* Register the 'primary' sidebar. */
			'id' => 'primary',
			'name' => __( 'Primary' ),
			'description' => __( 'A short description of the sidebar.' ),
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
			'after_widget' => '</div>',
			'before_title' => '<h3 class="widget-title">',
			'after_title' => '</h3>'

	/* Repeat register_sidebar() code for additional sidebars. */


It’s fairly simple stuff for most theme developers, yet so many themes have a mess when you look at their sidebar registration code.

Arguments for dynamic_sidebar()

The register_sidebar() function accepts a single parameter named $args, which is an array of arguments that define how the sidebar and its widgets should be handled. In the example above, each of these arguments were manually set.


The id argument is perhaps the most important argument you can set (see the “Bad sidebar code” section below on why you definitely need to set this). WordPress will use the ID to assign widgets to a specific sidebar, and you’ll use the ID to later load the sidebar.

Each ID should be unique to the sidebar. By default, WordPress sets this to sidebar-$i (where $i is a count of the registered sidebars).

'id' => 'primary',


The name argument is the human-readable label for your sidebar used in the WordPress admin. You can set this to anything you think best represents the name of your sidebar. Generally, sidebars are given a name that lets the user know where it’ll appear in the theme.

This argument can also be internationalized. So, make sure you set a proper textdomain when preparing your theme for translation. The default for this argument is Sidebar $i (where $i is a count of the registered sidebars).

'name' => __( 'Primary' ),


The description argument was introduced in WordPress 2.9. It allows you to set a specific description for how the sidebar is used within your theme. This argument defaults to an empty string. It can also be internationalized.

'description' => __( 'A short description of the sidebar.' ),


The before_widget argument is a wrapper element for widgets assigned to the sidebar. It should also be a block-level HTML element. This argument has a couple of things that you should always set with specific code so that plugins can properly use them, which is the id (%1$s) and class (%2$s) attributes.

By default, WordPress sets this as a list item: <li id="%1$s" class="widget %2$s">. I’m not a big fan of making sidebar widgets list items. I typically always go with a <div>.

'before_widget' => '<div id="%1$s" class="widget %2$s">',


The after_widget argument is pretty simple. It’s used as the closing wrapper for widgets assigned to the sidebar. You just need to close off the element you set for the before_widget argument. By default, WordPress sets this to </li>.

'after_widget' => '</div>',


Most widgets display a title if the user sets one. The before_title argument is the opening wrapper element for the sidebar’s widget titles.

By default, WordPress sets this to <h2 class="widgettitle">. I don’t like using an <h2> in this scenario. An <h3> or <h4> seems more semantic. I’m also not sure about the non-hyphenated class name, which makes it nearly unreadable.

'before_title' => '<h3 class="widget-title">',


The after_title argument is to close the wrapper element set in the before_title argument. By default, WordPress will set this to </h2>. You just need to make sure you set it to properly match the value you gave to the before_title argument.

'after_title' => '</h3>'

Displaying a dynamic sidebar

Once you’ve registered a dynamic sidebar, you’ll want to display it within your theme. WordPress has a function for this called dynamic_sidebar().

The dynamic_sidebar() function takes a single parameter of $index, which can either be the sidebar’s id or name argument (set when you registered the sidebar). While you can technically use either, it’s almost always safer to use the id you set.

Using the below code in one of your theme templates, you can display the primary sidebar, which we registered in the previous section. Note that I also used a wrapper element so the sidebar can be easily styled.

<div id="sidebar-primary" class="sidebar">

	<?php dynamic_sidebar( 'primary' ); ?>


Generally, this code would go within a file called sidebar-primary.php, which you’ll learn about in the “Sidebar templates” section later. However, dynamic_sidebar() can technically be called anywhere within your theme.

Displaying default sidebar content

Some themes developers may opt to display default content when a user hasn’t assigned any widgets to a specific sidebar. To check if a dynamic sidebar has any widgets, you would use the is_active_sidebar() conditional tag.

Like the dynamic_sidebar() function used to load the sidebar, is_active_sidebar() accepts a single parameter of $index, which should be the ID of the sidebar you want to check for active widgets.

With the below code, you can check if the primary sidebar has widgets. If so, display the widgets. Else, display some custom content.

<div id="sidebar-primary" class="sidebar">

	<?php if ( is_active_sidebar( 'primary' ) ) : ?>

		<?php dynamic_sidebar( 'primary' ); ?>

	<?php else : ?>

		<!-- Create some custom HTML or call the_widget().  It's up to you. -->

	<?php endif; ?>


Collapse sidebars without widgets

The previous example showed you how to display default content when a specific sidebar is inactive. But, you also have the option of completely collapsing (not showing any content) if the sidebar is inactive.

Again, you’ll use the is_active_sidebar() function to check if the primary sidebar has any widgets assigned to it.

<?php if ( is_active_sidebar( 'primary' ) ) : ?>

	<div id="sidebar-primary" class="sidebar">

		<?php dynamic_sidebar( 'primary' ); ?>


<?php endif; ?>

You can actually do some pretty interesting things with this. For example, you can create dynamic widths for your content depending on which sidebars are active/inactive. That’s a tutorial for another day though.

Sidebar templates

We’ve covered everything you need to know about using dynamic sidebars. Actually, there’s some other interesting functions if you feel like digging around the core WordPress code. For now, let’s take a look at sidebar templates.

Sidebar templates are typically used to house the code for a dynamic sidebar (see “Displaying a dynamic sidebar” above). The average WordPress theme has a single sidebar template called sidebar.php. If your theme has a single sidebar, this is all you’ll ever need.

Sidebar templates are loaded within a theme using the get_sidebar() function. The code below is what you would use to load a sidebar.php template:

<?php get_sidebar(); ?>

The get_sidebar() also accepts a single parameter of $name, which allows you to load a more-specific sidebar template. For example, the code below would call the sidebar-primary.php template.

<?php get_sidebar( 'primary' ); ?>

For the best organization of your theme and separation of code, you would create a specific sidebar template for each of your dynamic sidebars. Suppose you created two dynamic sidebars with the IDs of primary and secondary. To best organize these, create both a sidebar-primary.php and sidebar-secondary.php template for handling those sidebars.

You would use the code below to load both of these sidebar templates:

<?php get_sidebar( 'primary' ); ?>

<?php get_sidebar( 'secondary' ); ?>

The above is just the convention I use for sidebar templates. You can mix this up a bit to do things in a way that best suits you. The most important thing to do is make sure you use the get_sidebar() function when loading a sidebar template.

Note that sidebar templates don’t actually have to display dynamic sidebars. They can technically contain custom-coded content that displays anything. Remember, you can display a dynamic sidebar in any template as well.

Bad sidebar code

There are some common things I would like to see changed within themes. Not all of these things are technically incorrect, but they can present some unintended consequences or are just needless bits of code.

Problem #1: Randomly dropping code into functions.php

If you’re a theme developer, you should be familiar with WordPress’ built-in hooks. Not only should you be familiar with them, you should actually be using them.

The biggest issue I see is sidebar code just being dropped into functions.php. You should create a sidebar registration function and hook it to widgets_init. You can see an example of this in the “Registering a dynamic sidebar” section above.

The reason this is important is so that child themes (and even plugins) can know exactly when a sidebar was registered. This gives child themes the opportunity unregister a sidebar if needed. Plus, not doing it this way is just plain sloppy.

As a sidenote to this: You should never just drop code into functions.php. Always use the hooks WordPress provides to execute your functions when they should be executed in the WordPress flow.

Problem #2: Not setting sidebar IDs

Many people don’t realize this but when you don’t explicitly set a sidebar ID, you’re asking for trouble. When you use register_sidebar() or register_sidebars() without setting individual sidebar IDs, WordPress auto-creates these IDs by counting the number of registered sidebars and assigning a number as the ID.

This sounds great in theory. However, there’s a huge problem. When a plugin or child theme comes along and registers a new sidebar, this new sidebar gets the ID of 1 (if registered earlier in the flow), which alters the IDs of all the other sidebars. From an end user’s point of view, all of their widgets get assigned to a different sidebar.

Utter chaos.

Widgets are assigned to dynamic sidebars according to the sidebar ID. If that ID changes, the widgets appear to shift to a different sidebar. That’s why it’s important to manually set the sidebar IDs when registering a sidebar. Properly setting the ID is shown in the “Registering a dynamic sidebar” section above.

Another benefit of manually setting the ID is that you know exactly what the ID is for use in other functions such as dynamic_sidebar() and is_active_sidebar().

Problem #3: Backwards-compatiblity checks

The PHP function_exists() check is not needed. I’ve seen this in at least 80% of themes that I’ve looked at. As mentioned earlier in this post, dynamic sidebars have been around since 2007. The only reason to use this to check for sidebar functions is for backwards compability. However, most themes aren’t actually backwards compatible. And, backwards compatibility isn’t something I’d recommend beyond one version back.

One common check is to see if the register_sidebar() function is present as shown below. Forget about this check and simply register the sidebar.

if ( function_exists( 'register_sidebar' ) )

The same goes for a check of dynamic_sidebar(). Rather than checking if this function exists, simply call the sidebar.

if ( function_exists( 'dynamic_sidebar' ) )

Some people have a different opinion on backwards compatiblity. That’s fine. But, if you’re going to code one thing to be backwards compatible, then take it the distance by making the entire theme backwards compatible.

Problem #4: Not using get_sidebar()

When loading a sidebar template, I often see this code (or something similar):

include( TEMPLATEPATH . '/sidebar.php' );

This is not the proper way to load a sidebar template. WordPress has a function called get_sidebar() for handling this. Always use it as shown in the “Sidebar templates” section above. The reason you should use this function is because a specific hook (get_sidebar) is executed when this template is loaded, which plugins might use to handle specific features.

There are cases where get_sidebar() might not be appropriate for a specialized theme, but it’s something I’ve rarely seen.

Let’s update those sidebars

I’ve been reviewing some of the themes submitted to the WordPress themes repository over the last few months and figuring out how the theme review process works. I’ve literally looked at the code of 100s of themes in this time. Nearly every theme I’ve seen has at least one of the issues I described in the “Bad sidebar code” section of this article.

The goal is to help new and veteran theme developers create better-coded themes. This is only a single issue of many, many common issues I’m seeing in themes. I’ll probably write more on other issues in the future, but for the moment, I hope this article will help theme developers clean up their sidebar code.

credit :

Creating Menu in WordPress Admin side and using it in front side.

PHP Cookies: How to Set Cookies & Get Cookies

Cookies don’t have to be an essential part of a website but can provide some of the “little things” that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client’s computer so that you can access them next time they visit the website. Session ID’s are also usually held in cookies.

So what are the most popular uses of cookies? They are:

  • To store username/password information so that the user doesn’t have to log in every time they visit the website (“remember me” sign ins).
  • To simply remember the user’s name.
  • To keep track of a user’s progress during a specified process.
  • To remember a user’s theme.

Setting the Cookie

Setting a cookie requires a key, a value, and the amount of time to allow the cookie to exist.

$first_name = 'David';
setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day

Above, we set the user’s first name equal to ‘David’ (this data would actually come from a form or database but for the sake of the example we’ll use my name). Then, we set a cookie with the key of “first_name” with the value ‘David’, and program it to expire 7 days from now.

Getting the Cookie Values

Now that we’ve set our cookie, it’s time to get the value pretend they left your site and are coming back two days later).

echo 'Hello '.($_COOKIE['first_name']!='' ? $_COOKIE['first_name'] : 'Guest'); // Hello David!

Above, we check to see if the cookie with ‘first_name’ as the key still exists. If so, we use their name; if not, we call them “Guest”. Basic cookies are that easy!

PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.

setcookie('first_name',$first_name,time() + (86400* 7),'/~sugar/',',true,true);

This cookie is the same as above, but we’re also telling the cookie to be applied towards the “~sugar” directory on the “” domain. It is for use only on an SSL connection and it may not be used by JavaScript.

Some other things to know about cookies:

  • Although you set an expiration on the cookie, a user can delete cookies at any time.
  • Cookies can only be accessed by the browser that set them (Firefox and IE don’t share them)
  • A user can turn cookies off in their browser.
Hire Me
Follow Me!
Most Popular Articles & Pages
Because your vote is Important
Sorry, there are no polls available at the moment.