In Drupal 7, accessing field values in a custom template involves working with the field's machine name. If you've added an "announce" field to a content type, you need to ensure you know its machine name. This name is typically something like field_announce.
Here are the steps to access the "announce" field in a custom node template in Drupal 7:
-
Determine the machine name of the field:
- Go to Admin > Structure > Content types and select the content type where the "announce" field is added.
- In the list of fields, look for your "announce" field. The machine name will usually be shown in parentheses next to its label, e.g., "Announce (field_announce)".
-
Access the field in the template:
- In your custom node template (
node--content-type.tpl.php or similar), you can access the field values using the field's machine name.
Here is an example of how you can access and print the "announce" field value in your custom template:
<?php
// Ensure you've replaced 'field_announce' with the actual machine name of the announce field.
if (isset($node->field_announce['und']) && !empty($node->field_announce['und'])) {
// Get the first value (assuming it's a single-value field).
$announce_value = $node->field_announce['und'][0]['value'];
// Print the value.
print $announce_value;
}
?>
Explanation:
$node->field_announce['und']: The 'und' (undefined) language key is used by default unless you're working with a specific language, in which case you would replace 'und' with the appropriate language code.
[0]['value']: Accesses the first value of the field (if it's a single-value field; multi-value fields would require looping through the values).
Full Example in a Template:
Here is a more complete example within a node template:
<div class="node">
<h2><?php print $title; ?></h2>
<div class="content">
<?php print render($content); ?>
<?php if (isset($node->field_announce['und']) && !empty($node->field_announce['und'])): ?>
<div class="announce">
<?php
$announce_value = $node->field_announce['und'][0]['value'];
print $announce_value;
?>
</div>
<?php endif; ?>
</div>
</div>
In this example:
- The title of the node is printed.
- The main content of the node is rendered.
- The value of the "announce" field is accessed and printed inside a conditional check to ensure the field exists and is not empty.
Remember to clear your Drupal cache after making changes to the template to ensure your changes are reflected. You can clear the cache from the admin interface at Admin > Configuration > Development > Performance, or by using Drush (command line) with drush cache-clear all (or simply drush cc all).