Add custom Contextual Links to Drupal node teaser pages
I recently wanted to have a quicker way to unpublish my nodes in one of my 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<br>/**<br> * Implements hook_permission().<br> */<br>function YOUR_MODULE_permission() {<br> return array(<br> 'YOUR MODULE article unpublish articles' => array(<br> 'title' => t('YOUR MODULE Article Unpublish'),<br> ),<br> );<br>}<p>/**<br> * Implements hook_menu().<br> */<br>function YOUR_MODULE_menu() {<br> $items = array();</p><p> $items['node/%node/article/unpublish'] = array(<br> 'title' => 'Unpublish',<br> 'access callback' => '_YOUR_MODULE_article_unpublish_access_check',<br> 'access arguments' => array(1),<br> 'page callback' => '_YOUR_MODULE_article_unpublish',<br> 'page arguments' => array(1),<br> 'type' => MENU_LOCAL_TASK,<br> 'context' => MENU_CONTEXT_INLINE,<br> );</p><p> return $items;<br>}</p><p>/**<br> * Custom access check for node/%node/article/unpublish menu link.<br> *<br> * @param object $node Node object from menu argument.<br> * @return boolean TRUE if has access, FALSE otherwise.<br> */<br>function _YOUR_MODULE_article_unpublish_access_check($node) {<br> if ($node->type == 'article' && user_access('YOUR MODULE unpublish articles')) {<br> return TRUE;<br> }</p><p> return FALSE;<br>}</p><p>/**<br> * Callback action to unpublish article.<br> *<br> * @param object $node Node object.<br> */<br>function _YOUR_MODULE_article_unpublish($node) {<br> node_object_prepare($node);<br> $node->status = 0;<br> node_save($node);</p><p> watchdog('YOUR_MODULE', __FUNCTION__ . ' -- Unpublished article "%title" (NID: %nid).', array('%title' => $node->title, '%nid' => $node->nid), WATCHDOG_NOTICE);</p><p> $destination = drupal_get_destination();<br> $destination = isset($destination['destination']) ? $destination['destination'] : '<front>';<br> drupal_goto($destination);<br>}</p>
Tags: drupaldrupal 7contextual linkscustomnodeteaser