Show Different Number Of Posts Per Category In WordPress

WPRecipes has posted a way to set different number of posts for a WordPress category. It works nicely, but only for one category. And it uses custom query, which is not very familiar to newbies. In this post, we’ll do the same thing more simpler.

Assume that we want to show 5 posts per page for category “WordPress” and 10 posts per page for category “song”, just open the functions.php file in your theme folder and insert these line into it:

1.  add_action('pre_get_posts', 'diff_post_count_per_cat');
2.   
3.  function diff_post_count_per_cat() {
4.      if (is_admin()) return;
5.   
6.      $cat = get_query_var('category_name');
7.      switch ($cat) {
8.          case 'wordpress':
9.              set_query_var('posts_per_page', 5);
10.            break;
11.        case 'wordpress/song':
12.            set_query_var('posts_per_page', 2);
13.            break;   
14.    }
15.}

Change “wordpress” and “song” into real category names of your blog. Note that in the code above, we use category slug, not original name. If the category is a child category, don’t forget to insert full path (i.e. “wordpress/song” in the example below).


Change WordPress Default Email From Name And Address

By default, WordPress uses the from name “WordPress” and address “wordpress@yourdomain.com” when it sends notifications to users. It isn’t convenient and you might want to change it into your Blog name or something like that. This tutorial will show you how to do this just with some simple code.

Open the functions.php file of your theme and paste the following code into it:
  1. add_filter('wp_mail_from', 'new_mail_from');
  2. add_filter('wp_mail_from_name', 'new_mail_from_name');
  3.  
  4. function new_mail_from($old) {
  5. return 'admin@yourdomain.com';
  6. }
  7. function new_mail_from_name($old) {
  8. return 'Your Blog Name';
  9. }

Displaying A Login Form In Sidebar

Displaying A Login Form In Sidebar In WordPress

In WordPress 2.x and ealier, to display a login form in sidebar, we must use some raw PHP codes. But since version 3.0, WordPress provides new function, wp_login_form(), to make it done easily. In this article, we’ll see how the function wp_login_form() works and how to implement it in WordPress sidebar.

The function
wp_login_form() takes many parameters:
  wp_login_form(array(
     'echo' => true,
     'redirect' => site_url($_SERVER['REQUEST_URI']),     
      'form_id' => 'loginform',
    'label_username' => __('Username'),
      'label_password' => __('Password'),
     'label_remember' => __('Remember Me'),
     'label_log_in' => __('Log In'),
      'id_username' => 'user_login',
    'id_password' => 'user_pass',
    'id_remember' => 'rememberme',
    'id_submit' => 'wp-submit',
    'remember' => true,
    'value_username' => ,
    'value_remember' => false
));
The most important are:
  • echo: display (true) or not (false) login form. If not, it returns HTML string that you can put anywhere. Default is true.
  • redirect: the URL of web page to redirect user to after login. The default value is site_url( $_SERVER['REQUEST_URI'] ), that means current URL.
  • form_id: ID of login form. Default is loginform. You might want to know this for styling the login form.
  • remember: (true/false) Whether to remember the values. Default is true.
To see all parameters and their meanings, you can go to the Codex.
Now, let’s see an example of wp_login_form’s usage. We’ll check if user is logged in or not. If user logged in, we’ll display a greeting and a logout link. If not, we’ll display a login form. So, open your sidebar.php file and paste the following code into it:

  global $user_login;
  if (is_user_logged_in()) {
      echo 'Hello, ', $user_login, '. <a href="', wp_logout_url(), '" title="Logout">Logout</a>';
  } else {
      wp_login_form();
  }

That’s really simple and clean, isn’t it?
Adding a login form in sidebar is a good way to improve user experience in your WordPress blog, especially when you want your users do everything in the front-end only.


Plugin for Facebook widget in wordpress

1. Copy this code and  save it in plugins folder activate the plugin and enjoy.

<?php
/*

 * Plugin Name:Facebook Like widget

author: Arunendra Pratap Rai

*/

class apr_facebook_widget extends WP_Widget {

    /** constructor */

    function apr_facebook_widget() {

        parent::WP_Widget(false, $name = __('(apr) Facebook Like Box', 'ocmx'), $widget_options = __('Display a Facebook Like Box.','ocmx'));

    }

    /** @see WP_Widget::widget */

    function widget($args, $instance) {

        extract( $args );

        if(isset($instance["title"]))

$title = esc_attr($instance["title"]);

if(isset($instance["facebookpage"]))

$facebookpage = esc_attr($instance["facebookpage"]);

if(isset($instance["height"]))

$height = esc_attr($instance["height"]);

if(isset($instance["faces"]))

$faces = esc_attr($instance["faces"]);

if(isset($instance["colorscheme"]))

$colorscheme = esc_attr($instance["colorscheme"]);

if(isset($instance["stream"]))

$stream = esc_attr($instance["stream"]);

if(isset($instance["border"]))

$border = esc_attr($instance["border"]);      

     

echo $before_widget; ?>

<?php echo $before_title; ?>

            <?php echo $instance['title']; ?>

            <?php echo $after_title; ?>

            

         

        <?php echo $after_widget;

    }

    /** @see WP_Widget::update */

    function update($new_instance, $old_instance) {

        return $new_instance;

    }

    /** @see WP_Widget::form */

    function form($instance) {

        if(isset($instance["title"]))

$title = esc_attr($instance["title"]);

if(isset($instance["facebookpage"]))

$facebookpage = esc_attr($instance["facebookpage"]);

if(isset($instance["height"]))

$height = esc_attr($instance["height"]);

if(isset($instance["faces"]))

$faces = esc_attr($instance["faces"]);

if(isset($instance["colorscheme"]))

$colorscheme = esc_attr($instance["colorscheme"]);

if(isset($instance["stream"]))

$stream = esc_attr($instance["stream"]);

if(isset($instance["border"]))

$border = esc_attr($instance["border"]);

        ?>

            

<?php } } // class FooWidget //This sample widget can then be registered in the widgets_init hook: // register FooWidget widget add_action('widgets_init', create_function('', 'return register_widget("apr_facebook_widget");')); ?>

Redirect Users to Custom Pages by Role in wordpress

WordPress is being used more and more as a web application framework. With that use case comes a bunch of extra circumstances that WordPress doesn't cover. Do you really want your application users to see the WordPress admin? In my web application development experience, the answer to that question is usually "no." Today I'm going to teach you how to redirect a user based on their role to a custom page in WordPress. Getting Set Up Let's start this by building a plugin. You want this in a plugin because it's likely you'll change your theme design and still want the redirect functionality. Any functionality that you want to live past the current theme design should be in a plugin. Create a new plugin folder in your wp-content/plugins directory called 'cm-redirect-by-role' and add a file called cm-redirect-by-role.php. To that file we're going to add the basic WordPress plugin header seen below.
<?php
/*
Plugin Name: Redirect Users by Role
Plugin URI:
Description: Redirects users based on their role
Version: 1.0
Author: Arunendra Pratap Rai
*/
Now that you have a plugin started let's take a look at how user login works. User Login Flow The default spot that a user can log in to your WordPress site is via http://yoursite.com/wp-login.php. When you log in to a site from that location the site sends you to the WordPress admin dashboard. That means that the WordPress admin is starting up and you need to use an admin action to catch the user. I always hook the admin_init action since it runs late enough that you have access to user data but not so late that the user will see anything on the dashboard. Using the admin_init action means that even if they are already logged in and try to access the WordPress admin they will still get redirected. Now let's take a look at the code we are going to use. For our example we'll assume that we want to redirect all subscribers but this will work with any standard or custom role in WordPress.
function cm_redirect_users_by_role() {
    $current_user   = wp_get_current_user();
    $role_name      = $current_user->roles[0];
    if ( 'subscriber' === $role_name ) {
        wp_redirect( 'http://yoursite.com/dashboard' );
    } // if
} // cm_redirect_users_by_role
add_action( 'admin_init', 'cm_redirect_users_by_role' );
We start this process by getting our current user object with wp_get_current_user(). Out of that we get our role name and assign it to the $role_name variable. Then we check if $role_name matches with the role we want to redirect. If it does we use wp_redirect to send the user to our location of choice. While this will work we still have one more piece to add. Making It AJAX safe When making AJAX calls in WordPress you should always call the WordPress AJAX routing file which is inside the WordPress admin. If we leave our code as it is any AJAX call made by our matching roles will fail since it will meet our conditional and be redirected. To fix that we need to check if we are currently doing an AJAX call and if so skip the role check. function cm_redirect_users_by_role() {
    if ( ! defined( 'DOING_AJAX' ) ) {

        $current_user   = wp_get_current_user();
        $role_name      = $current_user->roles[0];

        if ( 'subscriber' === $role_name ) {
            wp_redirect( 'http://yoursite.com/dashboard' );
        } // if $role_name

    } // if DOING_AJAX

} // cm_redirect_users_by_role
add_action( 'admin_init', 'cm_redirect_users_by_role' );
Now we have our redirect function wrapped in a check for the DOING_AJAX constant. If that is defined, we are running an AJAX call and we want to skip the redirect code.

How to create Custom Meta Boxes in wordpress

Intro and Basic Fields There are a lot of tutorials on creating custom meta boxes, even just here on Wptuts, and it goes to show that having a good knowledge of these and a system for creating them is crucial to a successful WordPress theme or plugin project. In this series we won’t rehash what meta boxes are but instead we’ll create an easy system for plugging them into whatever your latest project is to keep your work moving consistently. Create a Meta Box As usual, the first step is to set up our code for creating a meta box. We’re just creating a library that we can come back to, so we’ll use a really generic name for everything. Some settings can also change whether you’re coming from a theme or a plugin, but the simplest way is to build it into a theme, so that’s what we’ll cover here. All of our code will either be placed into functions.php, or in a file that you include from functions.php in your theme.
// Add the Meta Box
function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // $id
        'Custom Meta Box', // $title 
        'show_custom_meta_box', // $callback
        'post', // $page
        'normal', // $context
        'high'); // $priority
}
add_action('add_meta_boxes', 'add_custom_meta_box');
This will add a meta box to the Write/Edit Post screen. • The $id will be added to the box as an id to make it easy to reference in style sheets and other functions • The $title will be displayed in the handle of the box • The $callback is the function we’ll use to define the output inside the box • $page is used to select which post type the box will be used on • We use $context to determine where the box will show up on the page • Having $priority set at “high” will put the box as close to the editor as we can and factors in other boxes added by core and plugins. Create the Field Array Since we’re building something that we can use over and over again, we won’t be defining the html for every field. Instead, we’ll create an array that holds all of the unique information for each field including a “type”. Then we’ll loop through each field and change the html output according to the type.
// Field Array
$prefix = 'custom_';
$custom_meta_fields = array(
    array(
        'label'=> 'Text Input',
        'desc'  => 'A description for the field.',
        'id'    => $prefix.'text',
        'type'  => 'text'
    ),
    array(
        'label'=> 'Textarea',
        'desc'  => 'A description for the field.',
        'id'    => $prefix.'textarea',
        'type'  => 'textarea'
    ),
    array(
        'label'=> 'Checkbox Input',
        'desc'  => 'A description for the field.',
        'id'    => $prefix.'checkbox',
        'type'  => 'checkbox'
    ),
    array(
        'label'=> 'Select Box',
        'desc'  => 'A description for the field.',
        'id'    => $prefix.'select',
        'type'  => 'select',
        'options' => array (
            'one' => array (
                'label' => 'Option One',
                'value' => 'one'
            ),
            'two' => array (
                'label' => 'Option Two',
                'value' => 'two'
            ),
            'three' => array (
                'label' => 'Option Three',
                'value' => 'three'
            )
        )
    )
);
It’s important that your meta fields have a unique key so a $prefix is defined to make it simple to attach the same one to each field id. Then we begin an array of arrays where each item defines a new field with a label, description, unique id, and the type of field it is. The select box has additional data to add all of the options for the select box. Using this template, you can add as many of each type of field you want. The order in which you add them to the array is the order in which they will output in the meta box. Outputting the Fields Now we are ready to set up our callback function and being outputting the html for each field.
// The Callback
function show_custom_meta_box() {
global $custom_meta_fields, $post;
// Use nonce for verification
echo '';
     
    // Begin the field table and loop
    echo '';
    foreach ($custom_meta_fields as $field) {
        // get value of this field if it exists for this post
        $meta = get_post_meta($post->ID, $field['id'], true);
        // begin a table row with
        echo '';
    } // end foreach
    echo '
'; switch($field['type']) { // case items will go here } //end switch echo '
'; // end table }
This code sets up the callback with a table for the fields and loops through each field in a table row. • Echo a hidden nonce field to verify the fields when we save them later • Start a table and begin a loop through each field from the $custom_meta_fields array. • Get the value of the field if it has been saved for the current post already so that we can output it in the field • Begin a table row with two cells: a for the label of the field, and a for the field itself. • Then we’ll insert our switch case items. • Finally, end the table row, the loop, and the table before closing the function Case: Text Input The basic idea here is to test what the field type is and change the output accordingly.
// text
case 'text':
    echo '
        
'.$field['desc'].''; break;
The idea here is pretty simple. • If the field type is “text”, echo the html code using that field’s array settings • The field id is used for the name which will create the meta field’s unique key, and it’s used for the field id which we want so that we can link our label to the field and also call it in our style sheet later if we want • The value will output the $meta variable which is empty if this field hasn’t been saved for this post yet. • After the field, we’ll output the description for further explanation of what is expected Case: Textarea
// textarea
case 'textarea':
    echo '
        
'.$field['desc'].''; break;
This follows the same principles as with the text field, except follows the standard of textarea html. The $meta is put between the opening and closing tags so that it outputs any saved text. Case: Checkbox
// checkbox
case 'checkbox':
    echo '
        ';
break;
A check box can be a little tricky because the value of $meta is used to determine whether or not the box should be checked. In our code we use an inline conditional that outputs the “checked” attribute if the $meta value exists, and nothing if it doesn’t. The other difference here is that we use the field’s description in another label so that there’s a large clickable area for the user. Case: Select Box
// select
case 'select':
    echo '
'.$field['desc'].''; break;
The select box is tackled in a completely new way. • Open the select field • Loop through each of the options that we defined in our array • Use an inline conditional to determine if the current option is the one saved for the post and output the “selected” attribute if it is • Close the select field and add the description Save the Data We’ve set up our basic box with a nice array template for using and reusing multiple types of fields. Now we need to loop through them again, verify them, and save them to the post.
// Save the Data
function save_custom_meta($post_id) {
    global $custom_meta_fields;
     
    // verify nonce
    if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) 
        return $post_id;
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $post_id;
    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id))
            return $post_id;
        } elseif (!current_user_can('edit_post', $post_id)) {
            return $post_id;
    }
     
    // loop through fields and save the data
    foreach ($custom_meta_fields as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    } // end foreach
}
add_action('save_post', 'save_custom_meta');
First we’ll go through a few security checks to see if the fields should be saved; nonce, autosave, and user capabilities are all checked. Then we loop through each field again. • Get the field’s value if it has been saved before and store it as $old • Get the current value that has been entered and store it as $new • If there is a $new value and it isn’t the same as old, update the post meta field with the $new value • If the $new value is empty and there is an $old value, delete the post meta field $old value • If there are no changes, nothing happens

How to add custom shipping method in woocommerce.

1.upload this file in plugins and activate it from dashboard you can change name of shipping method according to you. 

1.upload this file in plugins and activate it from dashboard you can change name of shipping method according to you.
<?php

/*
Plugin Name:Call for quata
Description: Call for quata shipping method plugin
Author:Arunendra Pratap Rai
*/
/**
* Check if WooCommerce is active
*/

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

function your_shipping_method_init() {

if ( ! class_exists( 'WC_Your_Shipping_Method' ) ) {

class WC_Your_Shipping_Method extends WC_Shipping_Method {

/**

* Constructor for your shipping class

*

* @access public

* @return void

*/

public function __construct() {

$this->id = 'call-for-quata'; // Id for your shipping method. Should be uunique.

$this->method_title = __( 'CALL FOR QUOTE' ); // Title shown in admin

$this->method_description = __( 'Description of CALL FOR QUOTE' ); // Description shown in admin

$this->enabled = "yes"; // This can be added as an setting but for this example its forced enabled

$this->title = "CALL FOR QUOTE"; // This can be added as an setting but for this example its forced.

 //$this->init_form_fields();

$this->init();

}

/**

* Init your settings

*

* @access public

* @return void

*/   

function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
 $this->cost  = $this->get_option( 'cost' );
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
 * Initialise Gateway Settings Form Fields
 */
 function init_form_fields() {
     $this->form_fields = array(
'enabled' => array(
        'title'         => __( 'Enable/Disable', 'woocommerce' ),
          'type'          => 'checkbox',
       'label'         => __( 'Enable CALL FOR QUOTE', 'woocommerce' ),
          'default'       => 'yes'
                        ),
     'title' => array(
          'title' => __( 'Title', 'woocommerce' ),
          'type' => 'text',
          'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),
          'default' => __( 'CALL FOR QUOTE', 'woocommerce' )
          ),
     'description' => array(
          'title' => __( 'Description', 'woocommerce' ),
          'type' => 'textarea',
          'description' => __( 'This controls the description which the user sees during checkout.', 'woocommerce' ),
          'default' => __("CALL FOR QUOTE Description", 'woocommerce')
           ),
'cost' => array(
                    'title'         => __( 'Default Cost', 'woocommerce' ),
'type'          => 'number',
'custom_attributes' => array(
'step'  => 'any',
'min'   => '0'
),
'description'   => __( 'Cost excluding tax. Enter an amount, e.g. 2.50.', 'woocommerce' ),
            'default'       => '',
          'desc_tip'      => true,
           'placeholder'   => '0.00'
                      )
     );
}
/**
* calculate_shipping function.
*
* @access public
* @param mixed $package
* @return void
*/
public function calculate_shipping( $package ) {
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => 'Call For Detail Coast',
'calc_tax' => 'per_item'
);

// Register the rate
$this->add_rate( $rate );
}
}
}
}
add_action( 'woocommerce_shipping_init', 'your_shipping_method_init' );
function add_your_shipping_method( $methods ) {
$methods[] = 'WC_Your_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_your_shipping_method' );
}
?>

How to add costum shipping method based on flat rate in woocommerce

1.upload this file in plugins and activate it from dashboard you can change name of shipping method according to you. 

<?php
/*

Plugin Name:Call for quata

Description: Call for quata shipping method plugin

Author:Arunendra Pratap Rai

*/

/**

* Check if WooCommerce is active

*/

if ( ! defined( 'ABSPATH' ) ) exit;

$dir = dirname(__FILE__);

include_once $dir.'/woocommerce/woocommerce.php';

class WC_Shipping_Flat_Rate extends WC_Shipping_Method {

     function __construct() {

         $this->id                       = 'call-for-quata';

        $this->method_title             = __( 'CALL FOR QUOTE', 'woocommerce' );

        $this->flat_rate_option         = 'woocommerce_flat_rates1';

       $this->admin_page_heading       = __( 'CALL FOR QUOTE', 'woocommerce' );

   $this->admin_page_description   = __( 'Description of Call For Quote', 'woocommerce' );

     add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );

   add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_flat_rates' ) );

         $this->init();

 }   

function init() {


      // Load the settings.

        $this->init_form_fields();

        $this->init_settings();

        // Define user set variables

         $this->title          = $this->get_option( 'title' );

         $this->availability   = $this->get_option( 'availability' );

        $this->countries      = $this->get_option( 'countries' );

        $this->type           = $this->get_option( 'type' );

        $this->tax_status     = $this->get_option( 'tax_status' );

        $this->cost           = $this->get_option( 'cost' );

        $this->cost_per_order = $this->get_option( 'cost_per_order' );

         $this->fee            = $this->get_option( 'fee' );

       $this->minimum_fee    = $this->get_option( 'minimum_fee' );

        $this->options        = (array) explode( "\n", $this->get_option( 'options' ) );

        // Load Flat rates

        $this->get_flat_rates();

    }


    /**

     * Initialise Gateway Settings Form Fields

      *

     * @access public

     * @return void

      */

    function init_form_fields() {

        global $woocommerce;


       $this->form_fields = array(

            'enabled' => array(

          'title'         => __( 'Enable/Disable', 'woocommerce' ),

                        'type'          => 'checkbox',

                            'label'         => __( 'Enable this shipping method', 'woocommerce' ),

                             'default'       => 'no',

                         ),

            'title' => array(

                            'title'         => __( 'Method Title', 'woocommerce' ),

                             'type'          => 'text',

                             'description'   => __( 'This controls the title which the user sees during checkout.', 'woocommerce' ),

                            'default'       => __( 'Flat Rate', 'woocommerce' ),

                            'desc_tip'      => true

                       ),

             'cost_per_order' => array(

                            'title'         => __( 'Cost per order', 'woocommerce' ),

                            'type'          => 'number',

                            'custom_attributes' => array(

                                'step'  => 'any',

                                 'min'   => '0'

                             ),

                             'description'   => __( 'Enter a cost (excluding tax) per order, e.g. 5.00. Leave blank to disable.', 'woocommerce' ),

                             'default'       => '',

                             'desc_tip'      => true,

                             'placeholder'   => '0.00'

                         ),

             'availability' => array(

                             'title'         => __( 'Method availability', 'woocommerce' ),

                            'type'          => 'select',

                            'default'       => 'all',

                             'class'         => 'availability',

                             'options'       => array(

                                'all'       => __( 'All allowed countries', 'woocommerce' ),

                                 'specific'  => __( 'Specific Countries', 'woocommerce' ),

                            ),

                         ),

             'countries' => array(

                             'title'         => __( 'Specific Countries', 'woocommerce' ),

                             'type'          => 'multiselect',

                             'class'         => 'chosen_select',

                             'css'           => 'width: 450px;',

                             'default'       => '',

                             'options'       => $woocommerce->countries->countries,

                         ),

             'type' => array(

                             'title'         => __( 'Calculation Type', 'woocommerce' ),

                            'type'          => 'select',

                             'default'       => 'order',

                            'options'       => array(

                                 'order'     => __( 'Per Order - charge shipping for the entire order as a whole', 'woocommerce' ),

                                 'item'      => __( 'Per Item - charge shipping for each item individually', 'woocommerce' ),

                                 'class'     => __( 'Per Class - charge shipping for each shipping class in an order', 'woocommerce' ),

                             ),

                        ),

             'tax_status' => array(

                             'title'         => __( 'Tax Status', 'woocommerce' ),

                             'type'          => 'select',

                             'default'       => 'taxable',

                             'options'       => array(

                                'taxable'   => __( 'Taxable', 'woocommerce' ),

                                 'none'      => __( 'None', 'woocommerce' ),

                            ),

                         ),

             'cost' => array(

                             'title'         => __( 'Default Cost', 'woocommerce' ),

                            'type'          => 'number',

                            'custom_attributes' => array(

                                 'step'  => 'any',

                                 'min'   => '0'

                             ),

                             'description'   => __( 'Cost excluding tax. Enter an amount, e.g. 2.50.', 'woocommerce' ),

                             'default'       => '',

                             'desc_tip'      => true,

                            'placeholder'   => '0.00'

                        ),

            'fee' => array(

                             'title'         => __( 'Default Handling Fee', 'woocommerce' ),

                             'type'          => 'text',

                            'description'   => __( 'Fee excluding tax. Enter an amount, e.g. 2.50, or a percentage, e.g. 5%. Leave blank to disable.', 'woocommerce' ),

                             'default'       => '',

                             'desc_tip'      => true,

                             'placeholder'   => '0.00'

                         ),

             'minimum_fee' => array(

                             'title'         => __( 'Minimum Fee', 'woocommerce' ),

                             'type'          => 'number',

                             'custom_attributes' => array(

                                 'step'  => 'any',

                                 'min'   => '0'

                             ),

                             'description'   => __( 'Enter a minimum fee amount. Fee\'s less than this will be increased. Leave blank to disable.', 'woocommerce' ),

                              'default'       => '',

                              'desc_tip'      => true,

                             'placeholder'   => '0.00'

                        ),

             'options' => array(

                             'title'         => __( 'Shipping Options', 'woocommerce' ),

                             'type'          => 'textarea',

                             'description'   => __( 'Optional extra shipping options with additional costs (one per line). Example: Option Name|Cost|Per-order (yes or no). Example: Priority Mail|6.95|yes. If per-order is set to no, it will use the "Calculation Type" setting.', 'woocommerce' ),

                             'default'       => '',

                             'desc_tip'      => true,

                             'placeholder'   => __( 'Option Name|Cost|Per-order (yes or no)', 'woocommerce' )

                         ),

             );

     } 

     /**

      * calculate_shipping function.

     *

      * @access public

     * @param array $package (default: array())

      * @return void

      */

     function calculate_shipping( $package = array() ) {

         global $woocommerce;

        $this->rates        = array();

         $cost_per_order     = ( isset( $this->cost_per_order ) && ! empty( $this->cost_per_order ) ) ? $this->cost_per_order : 0;


         if ( $this->type == 'order' ) {

             $shipping_total = $this->order_shipping( $package );

            if ( ! is_null( $shipping_total ) || $cost_per_order > 0 )

                 $rate = array(

                     'id'    => $this->id,

                     'label' => $this->title,

                     'cost'  => $shipping_total + $cost_per_order,

                 );

         } elseif ( $this->type == 'class' ) {

             $shipping_total = $this->class_shipping( $package );

             if ( ! is_null( $shipping_total ) || $cost_per_order > 0 )

                 $rate = array(

                     'id'    => $this->id,

                     'label' => $this->title,

                     'cost'  => $shipping_total + $cost_per_order,

                 );

         } elseif ( $this->type == 'item' ) {

             $costs = $this->item_shipping( $package );

             if ( ! is_null( $costs ) || $cost_per_order > 0 ) {

                 if ( ! is_array( $costs ) )

                     $costs = array();

                 $costs['order'] = $cost_per_order;

                 $rate = array(

                     'id'        => $this->id,

                     'label'     => $this->title,

                     'cost'      => $costs,

                     'calc_tax'  => 'per_item',

                 );

             }

         }

         if ( ! isset( $rate ) )

             return;

         // Register the rate

         $this->add_rate( $rate );

         // Add any extra rates

         if ( sizeof( $this->options ) > 0) foreach ( $this->options as $option ) {

             $this_option = preg_split( '~\s*\|\s*~', trim( $option ) );

             if ( sizeof( $this_option ) !== 3 ) continue;

            $extra_rate = $rate;

             $extra_rate['id']    = $this->id . ':' . sanitize_title($this_option[0]);

             $extra_rate['label'] = $this_option[0];

             $per_order_cost = ( $this_option[2] == 'yes' ) ? 1 : 0;

             $this_cost = $this_option[1];

             if ( is_array( $extra_rate['cost'] ) ) {

                 if ( $per_order_cost ) {

                     $extra_rate['cost']['order'] = $this_cost;

                 } else {

                     $total_quantity = 0;

                     // Shipping per item

                     foreach ( $package['contents'] as $item_id => $values )

                         if ( $values['quantity'] > 0 && $values['data']->needs_shipping() )

                             $total_quantity += $values['quantity'];

                     // Per-product shipping

                     $extra_rate['cost']['order'] = $this_cost * $total_quantity;

                 }

             } else {

                 // If using shipping per class, multiple the cost by the classes we found

                 if ( ! $per_order_cost && $this->type == 'class' ) {

                     $this_cost = $this_cost * $found_shipping_classes;

                 }

                 $extra_rate['cost'] = $extra_rate['cost'] + $this_cost;

             }

             $this->add_rate( $extra_rate );

         }

    }

     /**

      * order_shipping function.

     *

    * @access public

    * @param array $package

     * @return float

    */

     function order_shipping( $package ) {

         $cost   = null;

         $fee    = null;

         if ( sizeof( $this->flat_rates ) > 0 ) {

             $found_shipping_classes = array();

             // Find shipping classes for products in the cart

             if ( sizeof( $package['contents'] ) > 0 ) {

                 foreach ( $package['contents'] as $item_id => $values ) {

                     if ( $values['data']->needs_shipping() )

                         $found_shipping_classes[] = $values['data']->get_shipping_class();

                 }

             }

             $found_shipping_classes = array_unique( $found_shipping_classes );

             // Find most expensive class (if found)

             foreach ( $found_shipping_classes as $shipping_class ) {

                 if ( isset( $this->flat_rates[ $shipping_class ] ) ) {

                     if ( $this->flat_rates[ $shipping_class ]['cost'] > $cost ) {

                         $cost   = $this->flat_rates[ $shipping_class ]['cost'];

                         $fee    = $this->flat_rates[ $shipping_class ]['fee'];

                    }

                 } else {

                     // No matching classes so use defaults

                     if ( ! empty( $this->cost ) && $this->cost > $cost ) {

                         $cost   = $this->cost;

                         $fee    = $this->fee;

                     }

                 }

             }

         }

         // Default rates if set

         if ( is_null( $cost ) && $this->cost !== '' ) {

             $cost   = $this->cost;

             $fee    = $this->fee;

         } elseif ( is_null( $cost ) ) {

             // No match

             return null;

         }

         // Shipping for whole order

         return $cost + $this->get_fee( $fee, $package['contents_cost'] );

     }

     /**
     * class_shipping function.
         * @access public
     * @param array $package
    * @return float
    */
     function class_shipping( $package ) {
         $cost   = null;
         $fee    = null;
         if ( sizeof( $this->flat_rates ) > 0 ) {
             $found_shipping_classes = array();

             // Find shipping classes for products in the cart. Store prices too, so we can calc a fee for the class.

             if ( sizeof( $package['contents'] ) > 0 ) {

                 foreach ( $package['contents'] as $item_id => $values ) {

                     if ( $values['data']->needs_shipping() ) {

                         if ( isset( $found_shipping_classes[ $values['data']->get_shipping_class() ] ) ) {

                             $found_shipping_classes[ $values['data']->get_shipping_class() ] = ( $values['data']->get_price() * $values['quantity'] ) + $found_shipping_classes[ $values['data']->get_shipping_class() ];

                         } else {

                             $found_shipping_classes[ $values['data']->get_shipping_class() ] = ( $values['data']->get_price() * $values['quantity'] );

                         }

                     }

                 }

             }

             $found_shipping_classes = array_unique( $found_shipping_classes );

             $matched = false;
            // For each found class, add up the costs and fees
            foreach ( $found_shipping_classes as $shipping_class => $class_price ) {

                 if ( isset( $this->flat_rates[ $shipping_class ] ) ) {

                    $cost   += $this->flat_rates[ $shipping_class ]['cost'];

                     $fee    += $this->get_fee( $this->flat_rates[ $shipping_class ]['fee'], $class_price );

                     $matched = true;

                 } elseif ( $this->cost !== '' ) {

                    // Class not set so we use default rate if its set

                     $cost   += $this->cost;

                     $fee    += $this->get_fee( $this->fee, $class_price );

                     $matched = true;

                 }

             }

        }

         // Total

         if ( $matched )

             return $cost + $fee;

         else

             return null;

     }

    /**
     * item_shipping function.
 * @access public
 * @param array $package
 * @return array
     */

     function item_shipping( $package ) {

         // Per item shipping so we pass an array of costs (per item) instead of a single value

         $costs = array();

        $matched = false;

        // Shipping per item

         foreach ( $package['contents'] as $item_id => $values ) {

            $_product = $values['data'];

             if ( $values['quantity'] > 0 && $_product->needs_shipping() ) {

                 $shipping_class = $_product->get_shipping_class();

                 $fee = $cost = 0;


                if ( isset( $this->flat_rates[ $shipping_class ] ) ) {

                    $cost   = $this->flat_rates[ $shipping_class ]['cost'];

                    $fee    = $this->get_fee( $this->flat_rates[ $shipping_class ]['fee'], $_product->get_price() );

                     $matched = true;

                } elseif ( $this->cost !== '' ) {

                   $cost   = $this->cost;

                     $fee    = $this->get_fee( $this->fee, $_product->get_price() );

                     $matched = true;

                 }

                 $costs[ $item_id ] = ( ( $cost + $fee ) * $values['quantity'] );

             }

        }

         if ( $matched )

             return $costs;

        else

            return null;

    }

    /**

    * Admin Panel Options

     * - Options for bits like 'title' and availability on a country-by-country basis

    *

     * @since 1.0.0

     * @access public

   * @return void
    */

     public function admin_options() {

         global $woocommerce;

         ?>

         

admin_page_heading; ?>

admin_page_description; ?>

generate_settings_html(); ?>
: flat_rates ) { foreach ( $this->flat_rates as $class => $rate ) { $i++; echo ''; } } ?>
[?] [?]
id . '_class'] ) ) $flat_rate_class = array_map( 'woocommerce_clean', $_POST[ $this->id . '_class'] ); if ( isset( $_POST[ $this->id . '_cost'] ) ) $flat_rate_cost = array_map( 'woocommerce_clean', $_POST[ $this->id . '_cost'] ); if ( isset( $_POST[ $this->id . '_fee'] ) ) $flat_rate_fee = array_map( 'woocommerce_clean', $_POST[ $this->id . '_fee'] ); // Get max key $values = $flat_rate_class; ksort( $values ); $value = end( $values ); $key = key( $values ); for ( $i = 0; $i <= $key; $i++ ) { if ( isset( $flat_rate_class[ $i ] ) && isset( $flat_rate_cost[ $i ] ) && isset( $flat_rate_fee[ $i ] ) ) { $flat_rate_cost[$i] = number_format($flat_rate_cost[$i], 2, '.', ''); // Add to flat rates array $flat_rates[ sanitize_title($flat_rate_class[$i]) ] = array( 'cost' => $flat_rate_cost[ $i ], 'fee' => $flat_rate_fee[ $i ], ); } } update_option( $this->flat_rate_option, $flat_rates ); $this->get_flat_rates(); } /** * get_flat_rates function. * * @access public * @return void */ function get_flat_rates() { $this->flat_rates = array_filter( (array) get_option( $this->flat_rate_option ) ); } } ?>

Add a login/logout link to a WordPress navigation menu

1. Add the following code to your theme's functions.php file and change the menu area name if you are not using "primary". For WordPress 3.0 and up.
<?php
//Add login/logout link to naviagation menu

function add_login_out_item_to_menu( $items, $args ){


    //change theme location with your them location name

    if( is_admin() ||  $args->menu != 'main-menu' )

        return $items; 


    $redirect = ( is_home() ) ? false : get_permalink();

    if( is_user_logged_in( ) )

        $link = '' . __( 'Logout' ) . '';

    else  $link = '' . __( 'Login' ) . '';


    return $items.= '';

}add_filter( 'wp_nav_menu_items', 'add_login_out_item_to_menu', 10, 2 );

/**      END   **/   
?>