Archive for February, 2011


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 wordpress.com.

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 site1.example.com and site2.example.com
  • Sub-directories — like example.com/site1 and example.com/site2

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 127.0.0.1.
  • 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 *.example.com
  2. In the DNS records on your server, add a wildcard subdomain that points to the main installation. It should look like:
    A *.example.com

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.

CPanel

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

Plesk

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 xxx.xx.xx.xxx

(Replace “xxx.xx.xx.xxx” with your website IP.) Click “Admin Panel” (If you have no “admin panel” ask your host to do this.) -> Custom Httpd -> yourdomain.com -> 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 site1.example.com and site2.example.com
  • Sub-directories — like example.com/site1 and example.com/site2
Network Details
There are filled in automatically.
Server Address
The Internet address of your network will be example.com.
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 (13cc09.example.com) 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.

Permalinks

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 domain.com/blog/YYYY/MM/POSTNAME.

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. domain.com/PAGENAME. 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. domain.com/PAGENAME-2). 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. example.com/pagename ) and sites (i.e. example.com/sitename ). 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

Custom Account/Registration Fields

Our goal was to add a few fields to the standard Magento Registration form (Magento 1.4x, using the default template structure), enabling us to capture information such as Occupation, and Education.

Magento provides a simple user account signup page. However, some online stores might want to collect relevant customer information for more targeted and personal interactions with their customers. Some examples of details that could be collected include occupation, education etc…

Adding your custom fields on the signup form is not difficult, but it is not trivial either, since one cannot use the Magento backend for the task. As an example of how it can be done, I will demonstrate the addition of a new custom field to the signup form asking new users to enter their occupation and education.
Okay, Let me follow step by step. Please do not miss any single step otherwise it won’t work…
Step 1 :

Open File :

app\design\frontend\base\default\template\customer\form\register.phtml

1. Find below code

<div>
<label for="email_address"><?php echo $this->__('Email Address') ?> <span
class="required">*</span></label><br/>
<input type="text" name="email" id="email_address" value="<?php echo $this-
>htmlEscape($this->getFormData()->getEmail()) ?>" title="<?php echo $this->__('Email
Address') ?>" />
</div>

Replace Code

<div>
<label for="email_address"><?php echo $this->__('Email Address') ?> <span
class="required">*</span></label><br/>

<input type="text" name="email" id="email_address" value="<?php echo $this-
>htmlEscape($this->getFormData()->getEmail()) ?>" title="<?php echo $this->__('Email Address')
?>" />

</div>

<div>

<label for="occupation"><?php echo $this->__('Occupation') ?></label><br/>

<input type="text" name="occupation" id="occupation" value="<?php echo
$this->htmlEscape($this->getFormData()->getOccupation()) ?>" title="<?php echo $this-
>__('Occupation') ?>" />

</div>

<div>

<label for="education"><?php echo $this->__('Education') ?></label><br/>

<input type="text" name="education" id="education" value="<?php echo $this-
>htmlEscape($this->getFormData()->getEducation()) ?>" title="<?php echo $this->__('Education')
?>" />

</div>

step 2:

Open file :

app\design\frontend\base\default\template\customer\form\edit.phtml

1. Find Below Code

<li>
<div>
<label for="email"><?php echo $this->__('Email Address') ?> <span
class="required">*</span></label><br />
<input type="text" name="email" id="email" value="<?php echo $this-
>htmlEscape($this->getCustomer()->getEmail()) ?>" title="<?php echo $this->__('Email
Address') ?>" />
</div>
</li>

Replace Code

<li>
<div>
<label for="email"><?php echo $this->__('Email Address') ?> <span
class="required">*</span></label><br />
<input type="text" name="email" id="email" value="<?php echo $this-
>htmlEscape($this->getCustomer()->getEmail()) ?>" title="<?php echo $this->__('Email
Address') ?>" />
</div>
</li>

<li>
<div>
<label for="occupation"><?php echo $this->__('Occupation') ?> </label><br/>
<input type="text" name="occupation" id="occupation" value="<?php echo
$this->htmlEscape($this->getCustomer()->getOccupation()) ?>" title="<?php echo $this-
>__('Occupation') ?>" />
</div>
</li>

<li>
<div>
<label for="education"><?php echo $this->__('Education') ?> </label><br/>
<input type="text" name="education" id="education" value="<?php echo
$this->htmlEscape($this->getCustomer()->getEducation()) ?>" title="<?php echo $this-
>__('Education') ?>" />
</div>

</li>

Step 3:

Open file :

app\code\core\Mage\Customer\Model\Entity\Setup.php

1. Find below code inside getDefaultEntities() function

Replace Code :

'email' => array(
'type'
=> 'static',
'label'
=> 'Email',
'class'
=> 'validate-email',
'sort_order' => 6,
),
'occupation' => array(
'label'
=> 'Occupation',
'required' => false,
'sort_order' => 7,
),
'education' => array(
'label'
=> 'Education',
'required' => false,
'sort_order' => 8,
),

Note: (if you need field with validation then ‘requirted’ => true)

Hey do not feel tired or boring  you are going right way. You are now only Two steps to get it done.

Step 4 :

Open file :

app\code\core\Mage\Customer\etc\config.xml

1. Find below Code :

<global>
<fieldsets>
<customer_account>

Then In <customer_account>, you will find below line

<email><create>1</create><update>1</update></email>

After that line insert 2 more rows like below :

<occupation><create>1</create><update>1</update></occupation>
<education><create>1</create><update>1</update></education>

Step 5:

(Most important) Please follow below instruction :

1. Open file app\design\frontend\base\default\template\customer\form\register.phtml

2. Add Below code at top of the file,

<?php
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$AttrCode = occupation;
$settings = array (
'position' => 1,
'is_required'=> 0
);
$setup->addAttribute('1', $AttrCode, $settings); ?>

Now Save file Clear Cache from admin panel Refresh create account page

For Example, (http://websitename/ index.php/customer/account/create/)

Once Refreshed, then

Go to the customer_entity_varchar table in DB, your field is there…

Again Open file, app\design\frontend\base\default\template\customer\form\register.phtml

Now Replace Top code,

<?php
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$AttrCode = education;
$settings = array (
'position' => 1,
'is_required'=> 0
);
$setup->addAttribute('1', $AttrCode, $settings); ?>

Or Else put

$AttrCode = education;

Now Save file Clear Cache from admin panel Refresh create account page

For Example, (http://websitename/ index.php/customer/account/create/)

Once Refreshed then,

Again go to file, app\design\frontend\base\default\template\customer\form\register.phtml

And Comment Top Code or remove top code….

$AttrCode = education;

Now create your account and login with your information…

Check my account page and get smile….:)

That’s it…………….

Feel Free to ask if you are having any doubt in this.
credit goes to Magento developer : Vipul Prajapati

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:
    <?php
      $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) {
                                    $adon=1;
    ?>
    Replace this with Your adsense code!!!
    <?php
        }
     if(preg_match('/<p> /',$item)==0 && $tcount>=4 && $adon==1) {
                                    $adon=2;
    ?>
    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.
    <?php
       }
       $tcount++;
     }
    ?>
    

    credit goes to : zedomax.biz


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;
}
elseif(is_numeric($input))
{
$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);
}
else
{
$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 WPCode.net

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.

<?php

add_action( 'widgets_init', 'my_register_sidebars' );

function my_register_sidebars() {

	/* Register the 'primary' sidebar. */
	register_sidebar(
		array(
			'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.

id

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',

name

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' ),

description

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.' ),

before_widget

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">',

after_widget

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>',

before_title

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">',

after_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' ); ?>

</div>

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; ?>

</div>

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' ); ?>

	</div>

<?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 : justintadlock.com

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/','sudhirtiwari.com,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 “davidwalsh.name” 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.

How To Check Your PHP Installation? Please explain with example

PHP provides two execution interfaces: Command Line Interface (CLI) and Common Gateway Interface (CGI). If PHP is installed in the php directory on your system, you can try this to check your installation:

* Run “phpphp -v” command to check the Command Line Interface (CLI).
* Run “phpphp-cgi -v” command to check the Common Gateway Interface (CGI).

If you see PHP printing the version information on your screen for both commands, your installation is ok. Open a command window and run the commands below:

C:>phpphp -v
PHP 5.2.2 (cli) (built: May 2 2007 19:18:26)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0 Copyright (c) 1998-2007 Zend Technologies

C:>phpphp-cgi -v
PHP 5.2.2 (cgi-fcgi) (built: May 2 2007 19:18:25)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0 Copyright (c) 1998-2007 Zend Technologies

credit:www.globalguideline.com

How To Run a PHP Script? Please explain with example

A standard alone PHP script can be executed directly with the PHP Command Line Interface (CLI). Write the following script in a file called hello.php:

<?php echo “Hello world!”; ?>

This script can be executed by CLI interface like this:

phpphp hello.php

You should see the “Hello world!” message printed on your screen.

credit:www.globalguideline.com

How to Find a Substring from a Given String in PHP? Please explain with example

To find a substring in a given string, you can use the strpos() function. If you call strpos($haystack, $needle), it will try to find the position of the first occurrence of the $needle string in the $haystack string. If found, it will return a non-negative integer represents the position of $needle. Othewise, it will return a Boolean false. Here is a PHP script example of strpos():

<?php
$haystack1 = “2349534134345globalguideline16504381640386488129″;
$haystack2 = “globalguideline234953413434516504381640386488129″;
$haystack3 = “guideline234953413434516504381640386488129ggl”;
$pos1 = strpos($haystack1, “globalguideline”);
$pos2 = strpos($haystack2, “globalguideline”);
$pos3 = strpos($haystack3, “globalguideline”);
print(“pos1 = ($pos1); type is ” . gettype($pos1) . “n”);
print(“pos2 = ($pos2); type is ” . gettype($pos2) . “n”);
print(“pos3 = ($pos3); type is ” . gettype($pos3) . “n”);
?>

This script will print:

pos1 = (13); type is integer
pos2 = (0); type is integer
pos3 = (); type is boolean

“pos3″ shows strpos() can return a Boolean value

credit:www.globalguideline.com

source:stackoverflow.com
Hire Me
Follow Me!
Search
Most Popular Articles & Pages
Because your vote is Important
Sorry, there are no polls available at the moment.
Categories