Magento – Get customer gender from order

magento-1.7magento-1.8

I have made a query that gets customer's orders. Can I get customer gender based on this query? If not, how can I get customer gender? This is the code I have so far:

<?php

require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();

$productId = 297;

$orders = Mage::getModel('sales/order')->getCollection();
$orders
     ->getSelect()
     ->joinLeft(
     array(
          'order_item' =>Mage::getSingleton('core/resource')->getTableName('sales/order_item')),
          'order_item.order_id = main_table.entity_id',
          array('product_id'=>'product_id'))
     ->where('product_id=?', $productId)
     ->group('main_table.entity_id')
     ->order('main_table.entity_id DESC');

$fields = "date,company,name,country,city,address,postcode,itemname,quantity,price,sku \n";
foreach($orders as $order):

     $order->getData();
     $order->getIncrementId();
     $billingAddress = $order->getBillingAddress();
     $shippingAddress = $order->getShippingAddress();
     $billingStreet = $billingAddress->getStreet();

     $countryCode = $billingAddress->getCountry();
     $country = Mage::getModel('directory/country')->loadByCode($countryCode);

     $fields .=
          date('Y-m-d',strtotime($order->getCreatedAt())).','.
          $billingAddress->getCompany().','.
          $billingAddress->getName().','.
          $country->getName().','.
          $billingAddress->getCity().','.
          $billingStreet[0].','.
          $billingAddress->getPostcode().','.
          $order->getShippingDescription() .',';

          foreach ($order->getAllItems() as $itemId => $item):
               $itemname =  $item->getName();
               $itemname =  str_replace('&', " ", $itemname);
               $fields .=
                    $itemname. ','.
                    $item->getQtyOrdered().','.
                    $item->getPrice().','.
                    $item->getSku().',';

          endforeach;
     $fields = rtrim($fields, ',');
     $fields .= "\n";

endforeach;

$name = date('d-m-Y-H-i-s');
$output = fopen('backend/assets/csv/' . $name . '.csv', 'w');
fwrite ($output,$fields);
fclose ($output);

Best Answer

You can get the customer gender like this assuming you have the $order object:

$customer = $order->getCustomer();
if ($customer) { //check if the customer exists or is not guest
    $gender = $customer->getGender(); //this will return some id
    $genderText = $customer->getResource()
            ->getAttribute('gender')
                ->getSource()
                    ->getOptionText($customer->getData('gender')); //you get the label of the gender
}