2

How can I display Visitor's country name and flag and depending on his IP address in a block?

2

The Smart IP module can give you the user's IP address. The following code should give you a block, assuming you have flag images whose file names match the country code, e.g. "ie.png" for Ireland and those file are in "/sites/default/images".

function mymodule_block_info() {
  $blocks = array();
  $blocks['flag'] = array(
    'info' => t('Country flag')
  return $blocks;
}
function mymodule_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'flag' :
      $block['content'] = _flag_block_view();
      break;
  }
  return $block;
}
function _flag_block_view() {

  // Get the IP address
  $smart_ip_session = smart_ip_session_get('smart_ip');
  if ($smart_ip_session['location']['country_code']) {
     $code =  $smart_ip_session['location']['country_code'];
     $output = '<img src="/sites/default/files/images/' . strtolower($code) . '.png />';

  else {
    $output = "Nothing";
  }
  return $output;
}

The above is a simplistic solution. In practice you might want to make better provision for country codes and/or flag images not being available, add alt and/or title attributes to your tag, etc.

Also bear in mind you will need to choose a source of IP geolocation data. See this answer for info on that. And, remember geolocation data is not guaranteed to be 100% accurate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.