4

In my node.tpl.php file I have this custom code:

<?php if($node->field_division['und'][0]['value'] = 1): 
    $cta = $GLOBALS['base_url'].'/node/6';
elseif($node->field_division['und'][0]['value'] = 2): 
    $cta = $GLOBALS['base_url'].'/node/7';
endif;
?>

I want to move it to my template.php file, so I can access it both from node.tpl.php and page.tpl.php.

How can I do this?

I tried following the examples in this thread and this article but I can't get it to work. Any help would be greatly appreciated.

1 Answer 1

6

First off, don't use 'und'. You should use field_get_items(). This is a change from D6, which is likely why you can't use those articles as a reference.

Secondly, you are using = and not ==, so you're assigning the value instead of comparing it.

So, you can probably just do the following:

function THEMENAME_preprocess_node(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_preprocess_page(&$variables) {
  THEMENAME_field_division_helper($variables);
}

function THEMENAME_field_division_helper(&$variables) {
  if ($node = $variables['node']) {
    $field_division = field_get_items('node', $node, 'field_division');
    if ($field_division[0]['tid'] == 1) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
    else if ($field_division[0]['tid'] == 2) {
      $variables['cta'] = $GLOBALS['base_url'].'/node/6';
    }
  }
}

And then in your node.tpl.php and page.tpl.php file,

<?php if (isset($cta)): ?>
  <div class="some-wrapper">
    <?php print $cta; ?>
  </div>
<?php endif; ?>
7
  • Thanks for that! I tried it but it doesn't work. When $cta is placed in page.tpl/node/tpl, it doesn't print anything. I have tried clearing the cache and disabling and reinstalling the cache, but no success. Just to double check, the three functions go in template.php, right?
    – big_smile
    Jun 11, 2011 at 15:52
  • Yes, they do. You did change THEMENAME to your theme's name, right? Jun 11, 2011 at 16:28
  • Yes, I had changed THEMENAME to the theme's name. I also cleared the cache and disabled the the theme, set Bartik as the default, re-enabled the theme and then cleared the cache again to be on the safe side. However, despite all of this $cta doesn't print anything. I would be very grateful for any help you could offer.
    – big_smile
    Jun 11, 2011 at 16:41
  • Well, that means that field_division is never equal to 1 or 2, or it's using a database column other than 'value'. Enable the Devel module and check the node to see where the value is actually being stored. Jun 12, 2011 at 5:13
  • 1
    I've updated the code, switching 'value' to 'tid'. Should work now. Jun 13, 2011 at 14:10

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.