[Drupal] How to print a Flag Module flag anywhere on a Drupal site?

| | 1 min read

The Flag module in Drupal allows you to create different flags for your website. But the default settings in flag module will only allow you to display these flags under the user-profile page (if your flag type is user), OR under node page/node teaser/in contextual links (if your flag type is node).
If you want to display the flag information somewhere other than the above mentioned pages, you will find this article helpful.

To get the contents of a flag you can use the following:

$flag = flag_get_flags('flag_type'); // The flag type can be node or user. 

The function flag_get_flags() returns the available flags as flag objects.

Now to print a flag, use the following:

$output = '';
foreach ($flags as $flag) {  // Loops through the flag array
  $output .= '
'; // Prints the class name according to the flag. // Suppose your flag's name is follow, then it will have a class name flag-follow . $output .= $flag->theme($flag->is_flagged('Content_nodeid') ? 'unflag' : 'flag', 'Content_nodeid'); $output .= "
"; }

The function $flag->is_flagged('Content_nodeid') returns a boolean value and with respect to this value, we have to decide which flag is to displayed.
ie, if the function returns true, we've to display the 'unflag' link and if it returs false, we've to display 'flag' link.
The term 'content_nodeid' should be replaced with the node id, whose flag is to be displayed.