Magento – How to Get Current User’s Name in Layout XML File

customertoplinks

I want to add a top.links that shows user's name instead of "My Account".

In the old way, I've done by:

  1. Remove the line which add My Account link in customer.xml (usually in default handler)
  2. In page/template/links.phtml I add
$session = Mage::getSingleton('customer/session'); 
if($session->isLoggedIn()) {
    $customer = $session->getCustomer();
    $full_name =  $customer->getName();
    $this->addLink($label = $full_name, $url= $this->getUrl('customer/account'), $title='', $prepare = false, $urlParams = array(),
    $position = 10, $liParams = array('class' => 'my-class'), $aParams = null, $beforeText = '', $afterText = ''); 
}

But now, in new theme, I can't do this way because I use page/template/links.phtml for several kinds of links (account.links, checkout.links, top.links, …)

So, turn back to customer.xml,

<action method="addLink" translate="label title" module="customer">
      <label>My Account</label>
      <url helper="customer/getAccountUrl"/>
      <title>My Account</title>
      <prepare/>
      <urlParams/>
      <position>10</position>
</action>

How to replace "My Account" to user's name if user logged in? Is there any ways to get this done in customer.xml?

Best Answer

Goto app/code/core/Mage/Page/Block/Template/Links.php

copy to app/code/local/Mage/Page/Block/Template/Links.php then goto addLink() function goto

$link = new Varien_Object(array(

add below code

if($label=='My Account'):
         $loggedIn = Mage::getSingleton('customer/session')->isLoggedIn();
         if( $loggedIn){
            $label=Mage::getSingleton('customer/session')->getCustomer()->getName();
         }
        endif;

and My Account depend on xml code <label>My Account</label>

Related Topic