Friday, February 06, 2015

Arrays in PHP - 3


Let's try some more stuffs using PHP Arrays. Check the previous Array articles  Arrays in PHP - 2, Arrays in PHP

1. Problem :: How to get the last element in an array without using a loop.
Solution :: We need to use key() and end() functions in order to achieve this. Check out the code below.
   
   <?php
   // Define the Array
   $arr =  array( 's1' => "100", 's2' => 300, 's3' => 100, 's4' => 200, 's5' => 300 );
   
   // moves the array pointer to the end 
   // of the Array and return the value
   $l = end($arr);
   // Get that element's key
   $k = key($arr);
   // Print Key and Value
   echo "<br>$k :: $l";
   
   // Bring back the array pointer to the
   // beginning of the array
   reset($arr);
   
   // Get the Current item's key
   $k = key($arr);
   // Get the Value
   $l = current($arr);
   echo "<br>$k :: $l";
   // Print Key and Value
   echo "<br>$k :: $l";
 ?>   
   
   
2. Problem :: We have the following array and find all the keys where the value is 100.
   $arr =  array( 's1' => "100", 's2' => 300, 's3' => 100, 's4' => 200, 's5' => 300 );
   
  Solution :: We'll be using array_search() function which returns keys of the array. If we pass only the array name as the first parameter, all the keys are returned as array. However, if we give any value as second parameter, that value will be searched within the array and if found all respective keys are returned as array.
   
 <?php
   // Define the Array
   $arr = { 's1' => "100", 's2' => 300, 's3' => 100, 's4' => 200, 's5' => 300};
   
   // Print all Keys wihtin the array
   print_r( array_keys( $arr ) );
   
   // Print all keys where value is 100
   print_r( array_keys( $arr, 100 ) );
?>
   
   As PHP values can be implicitly typecast to other types (like integer to string), a string value "100" will be considered as a match while array_key() searches for integer 100.

3. Problem :: Passing Arrays to a function using call-by-reference.
   Solution :: As of PHP 5.3, passing arrays as reference to function is deprecated. To force it, we need to set 'allow_call_time_pass_reference' to true in php.ini.
   So, in general Arrays are passed by values to functions. Hence any changes made to the passed array within the called function does not make alterations to the original array. Here is a small example :
   
   <?php
   
   // Define the Array
   $arr =  array( "100", 300, 100, 200, 300 );
   
   // Define Function
   $f = create_function( '$a', '
for($i=0; $i<count($a);$i++)
 $a[$i]++;
   ');
   
   // Call Function
   $f($arr);
   
   // Print the Array
   echo '<br>After function call :: ';
   print_r ($arr);
 ?>
   
   The output of the above program will be same as the original array declared at the beginning of the program.

4. Strings can be treated as an array of characters. The same behaviour can be seen in C, C++ and Python. Check the code below ..
   
  <?php
   // Sample String
   $str = "This is a Balloon";
   
   // Start iterating with the  
   // index starting at zero
   for($i=0;$i<strlen($str);$i++)
     echo $str[$i];
 ?>

   The same is applicable to array of strings which can be printed character by character... just the way we do it in case of multi-dimensional arrays.  Check the example below :
   
  <?php
   // Declare array of Strings
   $arr = array( 
                "Jackie",
"Johnny",
"Varun",
"Catherine"
       ) ;
   // For loop to track strings
   for($i=0;$i<count($arr);$i++)
   { 
      echo "<br>";   
 
      // Now loop through characters in each strings
      for($j=0;$j<strlen($arr[$i]);$j++)
      {  
// Access each character as 
// a multi-dimensional arrays
echo $arr[$i][$j];
      }
   }
 ?>

Wednesday, January 14, 2015

Set Free-Shipping on certain products through observer in Magento 1.9

Scenario: We want to set Free Shipping if any Buyer purchases Product X and Product Y along with 0 or more other products from our Magento store.

Solution : We may create shopping cart rules to achieve this, but when I tried to do it, it did not work out. So, it is better to create a new Module and write an observer. That observer will apply the 'Free Shipping' to the cart when Product X and Product Y are found within the cart. But for this, the 'Free Shipping' shipping method must be enabled from Admin Panel.

For this, let's create the new module called 'Chandan_Freeshipping'. The required files to be created are as follows :

1. app/etc/modules/Chandan_Freeshipping.xml
2. app/code/local/Chandan/Freeshipping/etc/config.xml
3. app/code/local/Chandan/Freeshipping/Model/Observer.php

"Chandan" is the Namespace/Company name and module name is 'Freeshipping'

So, let's start with the first file Chandan_Freeshipping.xml. Here is its contents :

<?xml version="1.0"?>
<config>
    <modules>
        <Chandan_Freeshipping>
            <active>true</active>
            <codePool>local</codePool>
        </Chandan_Freeshipping>
    </modules>
</config>

Here we just mentioned that the corresponding module's files are stored in "local" codepool.

Now, the content of "config.xml" ...

<?xml version="1.0"?>
  <config>

   <modules>
    <Chandan_Freeshipping>
     <version>0.1.0</version>
    </Chandan_Freeshipping>
   </modules>

   <frontend>
    <events>
     <checkout_cart_product_add_after>
      <observers>
       <Chandan_Freeshipping_Model_Observer>
         <type>singleton</type>
        <class>
           Chandan_Freeshipping_Model_Observer
         </class>
         <method>checkfreeshipping</method>
      </Chandan_Freeshipping_Model_Observer>
      </observers>
     </checkout_cart_product_add_after>
     
     <checkout_controller_onepage_save_shipping_method>
      <observers>
       <Chandan_Freeshipping_Model_Observers>
        <type>singleton</type>
<class>
        Chandan_Freeshipping_Model_Observer
        </class>
        <method>applyfreeshipping</method>
       </Chandan_Freeshipping_Model_Observers>
      </observers>

      </checkout_controller_onepage_save_shipping_method>
       <paypal_prepare_line_items>
<observers>
        <Chandan_Freeshipping_Model_Observer_Paypal>
         <type>singleton</type>
          <class>
            Chandan_Freeshipping_Model_Observer
          </class>
          <method>applyfreeshipping</method>
        </Chandan_Freeshipping_Model_Observer_Paypal>
        </observers>
       </paypal_prepare_line_items>
    </events>
  </frontend>
 </config>

In the above XML, couple of points should be noticed : 

1. We are capturing 3 events 
   i. checkout_cart_product_add_after : The event is fired when a product is added to the cart. At this point, if we see product X and Y are within the cart, we just show a message like "You'll get the FreeShipping at the final Checkout". Check the screenshot below.
   
   

   

   ii. checkout_controller_onepage_save_shipping_method : This event is fired when Shipping method is saved in Final Checkout. Check the screenshot below.
   


   
   
Even though any other shipping method can be selected, but ONLY "Freeshipping" method will be finally applied as our observer is in work. Check the screenshot below.

  


   
   iii. paypal_prepare_line_items : This event is fired when user selects Paypal payment method and comes back to Order Review page. At that point of time, only one shipping method "FreeShipping" will be available to the purchaser as our observer captures this event and forces this method.

2. Check the construct of the event and observer mentioned in the above XML file.

<checkout_cart_product_add_after>
<observers>
  <Chandan_Freeshipping_Model_Observer>
 <type>singleton</type>
 <class>Chandan_Freeshipping_Model_Observer</class>
 <method>checkfreeshipping</method>
  </Chandan_Freeshipping_Model_Observer>
  </observers>
</checkout_cart_product_add_after>

The whole block is wrapped by tag having event name ('checkout_cart_product_add_after') being captured. Now the observer name is 'Chandan_Freeshipping_Model_Observer' having class name 'Chandan_Freeshipping_Model_Observer' and method name 'checkfreeshipping'. So, this 'checkfreeshipping' method of class 'Chandan_Freeshipping_Model_Observer' will handle the event.
     
3 different observers mentioned above have different names. It is better if these names are different from each other. For 3 events, we will create a new class 'Chandan_Freeshipping_Model_Observer' and the methods 'checkfreeshipping', 'applyfreeshipping' as mentioned in above XML. 

Next, let's check the content of Observer.php where, as said above, we need to define the observer class and its methods. 

<?php
class Chandan_Freeshipping_Model_Observer 

  
   // SKUs of Product X and Product Y
   private $fsprod1 = "acj0006s";
   private $fsprod2 = "acj003";  
   
   // A method which searches for Product X
   // and Product Y within the CART
   private function ifFreeShippingApplicable()
   {
    // Define an SKU array
     $sku_list = array();
    
    // GET CART Items
    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $cartItems = $quote->getAllVisibleItems();
 
    // LOOP Thru Cart Items
    foreach ($cartItems as $item)
     {
        $productId = $item->getProductId();
        $product = Mage::getModel('catalog/product')->load($productId);
      
        // Insert the Product SKU into that array
      $sku_list[] = $product->getSku() ;
    }
 
    // Check if Products X, Y are in the Cart
    if(in_array($this->fsprod1,$sku_list) && in_array($this->fsprod2,$sku_list))
    {
     return true;
    }
    else
    { 
     return false;
    }
    
   }
   
   // Show message that FreeShipping will
   // be applied on Cart
   public function checkfreeshipping(Varien_Event_Observer $observer) 
   { 
      if( $this->ifFreeShippingApplicable() )  
     {  
       // Product X and Y Found, 
      // Hence show Message
      Mage::getSingleton('checkout/session')->addSuccess("You will get Free Shipping at final checkout");
     }
   }
   
   // Method for applying the 'Freeshipping' method
   public function applyfreeshipping(Varien_Event_Observer $observer) 
   {
    // Check for Product X & Y
    if( $this->ifFreeShippingApplicable() )
    {
        // GEt Quote
$quote = Mage::getSingleton('checkout/session')->getQuote();

// Apply the Free Shipping
$address = $quote->getShippingAddress();
$address->setShippingMethod('freeshipping_freeshipping');
    }
   }  
}
?>

The code above is quite self-explanatory, it contains the class 'Chandan_Freeshipping_Model_Observer' and its methods which are executed when certain events are fired. 

Hope this helps.

Tuesday, January 06, 2015

How to do CURL by POSTing JSON data

This is already documented on PHP Manual, however very recently I had to do a CURL with some data JSON encoded and POSTed to a WebService to get some results. The corresponding PHP coding is not very difficult, I am showing it below.  

I am testing this in localhost and it is going to run perfectly. I have a file called test.php and I will be calling the same file ( other file is okay too ) with a parameter "curl=1" during the curl process. 

<?php

// The CURL handler
if( isset($_REQUEST['curl']) && $_REQUEST['curl'] == 1)
{
  // The below echo will be the CURL result
  echo print_r
         json_decode
           file_get_contents( "php://input" )
         ),1);
  exit;

}

// CURL URL
$curl_url = "http://127.0.0.1/test.php?curl=1";

// Data we are going to Submit/POST
$base_data = array( 
             "page" => 5,
             "showList" => "customer",
            "sortBy" => "salary",
            "orderBy" => "desc",
            "includePriceGroups" => true,
          "countryCode" => "US",
            "languageCode" =>"EN" );

// JSON Encoding the POST data
$post_data = json_encode( $base_data );

// CURL Process Init
$ch = curl_init( $curl_url );

// SET CURL Options
// Set the method to 'POST'
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
// Set the DATA
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);   

// GET The result as a string                                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
// SET the HEADER
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                         
    "Content-Type: application/json",                               
    "Content-Length: " . strlen($post_data))                         );                                                                                                                 
// GET the Result 
$result = curl_exec($ch);

// Show Result
echo "This Result:: " . $result;
?>

Though I have entered the "Content-type" header to be "application/json", but it can be "text/plain" also.


In the above scenario, this is what we get as output : 


stdClass Object
(
    [page] => 5
    [showList] => customer
    [sortBy] => salary
    [orderBy] => desc
    [includePriceGroups] => 1
    [countryCode] => US
    [languageCode] => EN
)


Now, let's find out, why the output is like that.  We are posting a data like this :


{ "page":5,"showList":"customer","sortBy":"salary", 
  "orderBy":"desc", "includePriceGroups":true, 
  "countryCode":"US", "languageCode":"EN"
}

It is in JS Object Notation format. We are getting the above data in CURL handler written at the top of the script : 

if( isset($_REQUEST['curl']) && $_REQUEST['curl'] == 1)
{
    echo print_r
         json_decode
           file_get_contents( "php://input" )
         ),1);
    exit;
}

We won't get this data in $_POST or $_REQUEST variables. To receive the post data, we need to call file_get_contents("php://input") i.e we are receiving it as an input stream. After that we convert it to a Object (of stdClass) by calling json_decode() function. Print_r() function finally print the object.

Hope this helps.

Thursday, December 18, 2014

How to log in/out Magento user to Wordpress blog - II

In the previous article How to log in/out Magento user to Wordpress blog - I, we have discussed how we can create Wordpress user during Magento 1.8 customer sign-up. Now we would check how we can make the user log in/out into/from Wordpress when the user signs in/out to/from Magento 1.8. 

As Wordpress functions are not available within Magento, we need to create a normal PHP page where we can include Wordpress core classes and use Wordpress functions for log in/out. So, when we call custom_login_wp.php?username=chandan&password=test123, this file calls Wordpress methods to log the user into Wordpress. Similarly, when we call custom_login_wp.php?logout=1 it logs the user out from Wordpress.

Our Wordpress folder is "wp" inside the Magento installation. We are creating this file "custom_login_wp.php" inside the "wp" folder, but it can be created anywhere. 

Let's check out the code in custom_login_wp.php.

<?php
// Include the  Wordpress Core
require("wp-load.php");   

// LOG OUT

if( isset($_GET['logout']) && $_GET['logout']== 1)
{
    // Log Out existing user
  if ( is_user_logged_in() ) { wp_logout(); }
    
}

// LOG IN

// Find URL Parameters in the URL
if(isset($_GET['username']) && $_GET['username']!="" && isset($_GET['password']) && $_GET['password']!="")
{
  
  // Log Out existing user
  if ( is_user_logged_in() ) { wp_logout(); }

  // GET Login Data from URL

  $creds = array();
  $creds['user_login']    = $_GET['username'];
  $creds['user_password'] = $_GET['password'];
  $creds['remember'] = false;

  // Wordpress LOGIN method
  $user = wp_signon( $creds, false );

  // ERROR  
  if ( is_wp_error($user) )
  {
   echo $user->get_error_message(); 
  }
}

// Always return the user to where

// Magento wanted to redirect
header("location:" . $_GET['current_url'] );
?>

The last line is a redirect; we better redirect the user to a URL where Magento user goes after a successful log in. So, in that case we need to call the custom_login_wp.php as shown below ::

custom_login_wp.php?username=chandan&password=test123&current_url=http://example.com/customer/account

Check out the "current_url" parameter ... it specifies where to return within Magento after Wordpress Log in.

Some points to be noticed here :

1. To Log any Wordpress user out, we use Wordpress function wp_logout()
2. To check if any user is logged in, we use Wordpress function is_user_logged_in()
3. To Log a user in, we use Wordpress function wp_signon()

Next let's check out the "loginPostAction()" method in Mage Customer's AccountController.php file which is responsible for logging the user into Magento. We need to append our Wordpress Login code to this method. We just need to remember here that during Wordpress signup, we had used the user's Firstname as Wordpress username and user's Magento password as Wordpress password. Here is the loginPostAction() method. 

<?php
public function loginPostAction()
{
  ...

  try 
  {
    $session->login($login['username'], $login['password']);

    if ($session->getCustomer()->getIsJustConfirmed()) 
    {
  $this->_welcomeCustomer($session->getCustomer(), true);
    }

    ////*** OUR CUSTOM CODE STARTS HERE **////
    /// At this position, user is successfully
    /// Logged into Magento, Now it's our scope to
    /// log the user into Wordpress
    /// Let's get username and password

    $customer       = $session->getCustomer();
    $first_name     = $customer->getFirstname();
    $user_pwd       = $login['password'];

    /// Build URL to our custom page "custom_login_wp.php"
    $base_url = str_replace("/index.php","",Mage::getBaseUrl()) ;
    $target_url = $base_url . "wp/custom_login_wp.php?username=$first_name&password=$user_pwd&current_url=";

    // Check if Magento redirects to DashBoard
    $rdrct2Dashb = Mage::getStoreConfigFlag( Mage_Customer_Helper_Data::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD );

    // If Not DashBoard
    if(!$rdrct2Dashb)
    {
        $p = $base_url;
    }
    // Redirect to CUstomer DashBoard
    else
    {
        $p = "{$base_url}index.php/customer/account";
    }

    // Final URL is ready
    $target_url .= $p;


    //// REDIRECT User for a WORDPress Login
    if (!headers_sent()) 
    {
header( "Location:$target_url" ); exit;
    }
    ////*** OUR CUSTOM CODE ENDS HERE ***////

 } 
 catch (Mage_Core_Exception $e) 
 {
...
 } 
 catch (Exception $e) 
 {
...
 }

 ...
}
?>

Some points need to be noticed here : 

1. We take the Magento user's first name as Wordpress username. We get the user's first name with the statement $customer->getFirstname();
2. We extract the password user gives at Magento login prompt from the POST data stored in $login['password'].
3. In Magento Admin Panel, there is a provision to choose whether the customer will be redirected to Dashboard after login. So, we get that option's value by calling Mage::getStoreConfigFlag() with appropriate parameter. So, if that option is set to 'Yes', we would redirect the customer to Dashboard after we Log him into Wordpress (in custom_login_wp.php). Any other logic can be easily implemented here also.

Next, we would look into the Logout part. The Magento method logoutAction() inside Mage_Customer's AccountController.php file, is called when Magento user is logged out. So, we need to call the same file custom_login_wp.php we have written earlier with parameter "logout=1". 

Check out the code below. 

<?php
public function logoutAction()
{
  $this->_getSession()->logout()->renewSession();

  ///**** Our Custom Code Starts ****//
  /// LOG OUT the USER from WordPress also
  /// Build the URL
  $base_url = str_replace("/index.php","",Mage::getBaseUrl()) ;
  $return_url = rtrim($base_url,"/") . "/index.php/customer/account/logoutSuccess/";
  
  $target_url = $base_url . "wp/custom_login_wp.php?logout=1&current_url=" . $return_url;

  if (!headers_sent()) 
  {
  header( "Location:$target_url" ); exit;
  }
  
  ///**** Our Custom Code Ends ****//
  $this->_redirect('*/*/logoutSuccess');
}
?>

Hope this helps. Another thing, we should not modify core files. It is always a good practice to create our own module to do such custom coding. Check the article "How to override Customer Account controller in Magento 1.8" to see how we can create our own Customer module extending the original Mage Customer module.

Monday, December 08, 2014

How to log in/out Magento user to Wordpress blog - I

This is a case where Wordpress blog is integrated inside Magento and we want a single sign-up/login/logout for users. It means the following things ::

1. Wordpress is installed in any subfolder within Magento installation.
2. When a user signs up for Magento, he is automatically signs up for Wordpress. Actually a new user needs to be created manually in Wordpress.
3. When a user logs on in Magento, he is also logs in Wordpress.
4. When a logged-in user logs out from Magento, he is also logged out from Wordpress.

As Magento user is automatically registered to Wordpress, the default Wordpress sign-up/registration should be disabled. To disable wordpress sign-up, we need to go to Settings > General in Wordpress Admin Panel and uncheck the option "Anyone Can Register".

Now, for our working, we need to know that sign-up, login and logout procedures are handled by AccountController.php inside the path app/code/core/Mage/Customer/controllers. So, the module name is Mage_Customer and the controller class name is Mage_Customer_AccountController.

We need to edit the AccountController.php and put our custom code inside it. Let's check out the registration process. There is an action called "createPostAction" which registers a Magento user. The form on registration page has an action "http://127.0.0.1/magento/customer/account/createpost/" (on my local machine), so the function createPostAction() is responsible for creating the customer account.  

First check out the final code below, then analyze it. Our Custom code is shown in blue below. Whole function is not shown below... only the section where customization is needed is shown.

<?php
public function createPostAction()
{
  ......
 
  $customer = $this->_getCustomer();

  // GET CUSTOMER PASSWORD
  $pwd = $this->getRequest()->getPost('password'); 

  try 
  {
    $errors = $this->_getCustomerErrors($customer);
         if (empty($errors)) 
    {

$customer->save();
$this->_dispatchRegisterSuccess($customer);

// PUT The password in SESSION
// So That we can LOG him in WordPress also
Mage::getSingleton('core/session')->setPwd($pwd);

$this->_successProcessRegistration($customer);
return;
    } 
    else 
    {
$this->_addSessionError($errors);
    }
  } 
  catch (Mage_Core_Exception $e) 
  {
     ...
  }

  catch (Exception $e) 
  {
     ...
  }
?>

The above piece of code accepts user inputs, processes and validates by calling other functions like _getCustomerErrors(), and finally saves the new customer (if everything is fine) information to DB through the statement $customer->save() and finally calls the _successProcessRegistration() function to show Success Message, send mails and other tasks. Now we are supposed to create a Wordpress account with an username and password; username can be created from user's first name which can be retrieved any time, it is difficult to retrieve the password. Hence we had to receive the password from the user and put it on session. Now  let's make a little changes to the function _successProcessRegistration().

<?php
protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
{
  $session = $this->_getSession();
  if ($customer->isConfirmationRequired()) 
  {
     ...

     // at the end of existing code 
     // INSERT the USER into WORDPRESS
     $this->insertToWordpress( $customer, $c );
  } 
  else 
  {

     // before the existing code
     // INSERT the USER into WORDPRESS
     $this->insertToWordpress( $customer, $c );

     ...
  }

  $this->_redirectSuccess($url);
  return $this;
}
?>

So, we just call our custom function insertToWordpress() from within _successProcessRegistration() to create new wordpress user. Check out the code for insertToWordpress() below.

<?php
protected function insertToWordpress(Mage_Customer_Model_Customer $customer, $customer_group)
{
 
  // Create Capabilities
  $usr_typ_arr["author"] = true;
  
  $session = $this->_getSession();

  // Customer ID
  $Magento_customer_ID = $customer -> getId();  
  
  // GET Tables 
  $wp_user_table = "wp_users";
  $wp_usermeta_table = "wp_usermeta";
  
  // GET Fields which will be written to USER TABLE
  $user_login      = $customer->getFirstname();
  $user_pass       = md5( Mage::getSingleton('core/session')->getPwd() );
  $user_nicename   = $user_login;
  $user_email      = $customer->getEmail();
  $user_url        = "";
  $user_registered = date("Y-m-d h:i:s");
  $user_activation_key = "";
  $user_status     = 0;
  $display_name    = $user_login;
  
  // Unset PASSWORD from SESSION
  Mage::getSingleton('core/session')->unsPwd();
  
  // DEFINE DB Handle
  // To read from the database
  $read  = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' ); 
  // To write to the database
  $write = Mage::getSingleton( 'core/resource' )->getConnection( 'core_write' ); 
  
  // GET Table Name
  $userTable = Mage::getSingleton( 'core/resource' )->getTableName( $wp_user_table );
  
  $userMetaTable = Mage::getSingleton( 'core/resource' )->getTableName( $wp_usermeta_table );
  
  // INsert into USER Table
  $query = "INSERT into " . $userTable . " values ('', '$user_login', '$user_pass', '$user_nicename', '$user_email', '$user_url', '$user_registered', '$user_activation_key', '$user_status', '$display_name')";
  $write->query( $query );
  
  // GET Last Insert ID (user ID)
  $last_insert_id = $write->lastInsertId();
  
  // BUIL SQL for Inserting into user Meta Table
  $q = array();
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'first_name','".$customer->getFirstname()."')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'last_name','".$customer->getLastname()."')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'nickname','$user_nicename')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'description','')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'rich_editing','true')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'comment_shortcuts','false')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'admin_color', 'fresh')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'use_ssl', '0')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'show_admin_bar_front', 'true')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'wp_capabilities', '".serialize($usr_typ_arr)."')";
  
  // 2 for Author, who can manage/publish their content
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'wp_user_level', '2')"; 
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'dismissed_wp_pointers',  'wp350_media,wp360_revisions,wp360_locks,wp390_widgets')";
  $q[] = "INSERT into $userMetaTable VALUES('','$last_insert_id', 'magento_user_id',  '$Magento_customer_ID')";
  
  // ACTUAL INSERT to User Meta Table
  for($i=0;$i<count($q);$i++) 
     $write->query( $q[$i] );

}
?>

The above function builds some values out of customer object, and then makes entries to wordpress "user" and "usermeta" tables. The "usermeta" table in Wordpres holds various information about the user including user capabilities and user level. As said earlier, we are using the customer's first name as Wordpress login name and Magento password as Wordpress password. After we create the Wordpress user, we unset the password we had put in session by calling Mage::getSingleton('core/session')->unsPwd();  

This way, we create users for both Magento and Wordpress. 

So, the Registration process is complete. For logging in/out simultaneously in Magento and Wordpress, check the part 2 of this article How to log in/out Magento user to Wordpress blog - II