1

I have created a new content type programmatically and I would like to set permission so that anonymous users do not see this content when it is published.

How can I do this?

3 Answers 3

3

By default, Drupals permission system does not support specific view permissions by content types. You will need a module for that. Have a look at Controlling Access to Content Overview. In Drupal 6 projects I have used Taxonomy access control lite quite offen.

1

Assuming Drupal 7, you can look into hook_node_access(), eg, something along these lines:

function YOURMODULE_node_access($node, $op, $account) {

  // If $node is a string, the node has not yet been created and we don't care about that case.

  if (is_string($node)) {
    return NODE_ACCESS_IGNORE;
  }

  $type =  $node->type;

  if ($op == 'view' && $type == 'YOUR_CONTENT_TYPE' && !$account->uid) {
    return NODE_ACCESS_DENY;
  }

  return NODE_ACCESS_IGNORE;

}

A good place to look for more information on this would be the node_access_example module inside the Examples Module.

1
  • this is a good, lighter alternative to contrib modules
    – Augusto
    Apr 14, 2015 at 11:00
-1

You could use a custom module that:

  • add a permission for every content type
  • modify permissions to node/nid with hook_menu_alter

Obviously you can create a permission only for your custom content type.

Here is an example:

<?php 
/**
 * Implements hook_permission.
 */
function mymodule_permission() {
  $permissions = array();  
  foreach (node_type_get_types() as $type) {
    $permissions['view ' . $type->name . ' contents'] = array (
      'title' => t('View published contents for ' . $type->name . ' nodes'),      
      'description' => t('Let users to see nodes of type ' . $type->name),
    );
  }   
  return $permissions;
}

/**
 * Implements hook_menu_alter.
 */
function mymodule_menu_alter(&$items) {
  $items['node/%node']['access arguments'] = array(1);
  $items['node/%node']['access callback'] = 'mymodule_check_permission';
} 

/**
 * Check permission
 */
function mymodule_check_permission() {
  global $user;
  if ($node->status == 1) {
    if (user_access('view ' . $node->type . ' contents', $user) || user_access('administer nodes', $user))) {
      return TRUE;
    }
  else {
    return user_access('access content', $user);
  }
}
?>
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.