Get users who flagged a node

Get users who flagged a node

This article will explain how to get users who flagged a node in drupal. Drupal provides a contributed module named Flag module which is used to create unlimited arbitrary flags or bookmarks to flag content.

In one for the Drupal project we had a requirement to get users who flagged a node and display their details when ever that node is viewed in the browser.

To get users who flagged a node, here node can be any thing like blog post, user, content type etc… we need to invoke flog module in our custom module or block that has to display the users list.

Use below code to get all the users who had flagged a particular node.

Step 1 :  To get the node ID from URL

if (arg(0) == 'node') {
  $nid = arg(1);

Step 2 :  Using node ID get users who flagged a node.

$user_ids=array(); //User Array initialization 
$nid = 2; //node ID
  $flags = module_invoke('flag', 'get_content_flags', 'node', $nid);
  if (isset($flags)) {
    foreach ($flag as $uid => $data) {
       $user[] = $uid; //Adds user ids to the user array.

To get User pictures user below code

if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  $nid = $node->nid;
  $accounts = module_invoke('flag', 'get_content_flags', 'node', $nid);
  if (isset($accounts)) {
    foreach ($accounts as $uid => $data) {
      $account = user_load(array('uid' => $uid));
      print theme('user_picture', $account); //Substitute this with whatever you'd like to display from the user.

To read more about Drupal from here

Leave a Reply

Your email address will not be published. Required fields are marked *