How to display node hit in drupal?
To display the hit count of a node in Drupal, you can use the Statistics module and a custom code snippet. Here's how you can do it:
Enable the Statistics module: Go to the Extend page (/admin/modules) in your Drupal admin interface. Locate the "Statistics" module and enable it. Save the configuration.
Create a custom module (optional): If you don't already have a custom module set up, you can create one. Create a folder for your module in the /modules directory of your Drupal installation. Inside the module folder, create the necessary files ( modulename .info.yml and modulename .module). Replace " modulename" with the name of your custom module.
Implement hook_preprocess_HOOK(): Open your custom module's modulename .module file and implement the hook_preprocess_HOOK() function, where HOOK is the machine name of the theme or template you want to preprocess. In this case, we'll preprocess the node template. Add the following code to your module file:
/**
* Implements hook_preprocess_HOOK() for node templates.
*/
function modulename_preprocess_node(&$variables) {
// Get the current node object.
$node = $variables['node'];
// Check if the Statistics module is enabled.
if (\Drupal::moduleHandler()->moduleExists('statistics')) {
// Get the total view count for the node.
$total_views = \Drupal::service('statistics.storage.node')->fetchViewCount($node->id());
// Set the view count as a variable to be used in the node template.
$variables['total_views'] = $total_views;
}
}
Clear the cache: After adding the code, clear the Drupal cache to ensure that the changes take effect.
Now, you can display the hit count in your node template. Edit the appropriate node template file (node.html.twig or a custom node template file) in your theme and add the following code where you want to display the hit count:
{{ total_views }} views
Save the template file, and the hit count should now be displayed when viewing nodes.
Remember to replace " modulename " with the actual name of your custom module, and adjust the template file name according to your theme's structure if needed.