How to add custom Contextual Links to Drupal node teaser pages

Some time we need a quicker way to unpublish nodes in Drupal project with Contextual Links.

This mini code snippet will show you how to create a custom module to add links to the contextual shortcut (as seen in screenshot).

The code will also have a custom access check to only show the link for certain content type and custom permission.

 

<?php
/**
* Implements hook_permission().
*/
function YOUR_MODULE_permission() {
  return array(
    'YOUR MODULE article unpublish articles' => array(
      'title' => t('YOUR MODULE Article Unpublish'),
    ),
  );
}
/**
* Implements hook_menu().
*/
function YOUR_MODULE_menu() {
  $items = array();
  $items['node/%node/article/unpublish'] = array(
    'title' => 'Unpublish',
    'access callback' => '_YOUR_MODULE_article_unpublish_access_check',
    'access arguments' => array(1),
    'page callback' => '_YOUR_MODULE_article_unpublish',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
  );
  return $items;
}
/**
* Custom access check for node/%node/article/unpublish menu link.
*
* @param object $node Node object from menu argument.
* @return boolean TRUE if has access, FALSE otherwise.
*/
function _YOUR_MODULE_article_unpublish_access_check($node) {
  if ($node->type == 'article' && user_access('YOUR MODULE unpublish articles')) {
    return TRUE;
  }
  return FALSE;
}
/**
* Callback action to unpublish article.
*
* @param object $node Node object.
*/
function _YOUR_MODULE_article_unpublish($node) {
  node_object_prepare($node);
  $node->status = 0;
  node_save($node);
  watchdog('YOUR_MODULE', __FUNCTION__ . ' -- Unpublished article "%title" (NID: %nid).',
 array('%title' => $node->title, '%nid' => $node->nid), WATCHDOG_NOTICE);
  $destination = drupal_get_destination();
  $destination = isset($destination['destination']) ? $destination['destination'] : 
'<front>';
  drupal_goto($destination);
}

 

4 thoughts on “How to add custom Contextual Links to Drupal node teaser pages

  1. I love what you guys tend to be up too. This type of clever work and reporting!
    Keep up the very good works guys I’ve included you guys
    to my blogroll.

  2. Hello Theгe. I found үour blog using msn. This is a
    vеry well wгitten article. I’ll Ьe sure tߋ
    bookmark it ɑnd come ƅack to reɑԁ more of yߋur useful info.
    TҺanks for the post. I’ll Ԁefinitely comeback.

  3. Asking questions are genuinely nice thing should you be not understanding anything completely, however this paragraph presents pleasant understanding yet.

  4. Heya i’m for the principal time here. I found this board and that i in finding It truly helpful & it
    helped me to out much. I’m hoping to present something again and help others such as you helped me.

Leave a Reply

Your email address will not be published.