Drupal 7 redirect to last published node of a specific node type
Snippet
Yeah, kitt finished writing this at 22:28 on 9 January 2016
Okay, you have a number of node of a particular content type, say, a Daily Photo, and you want a link, say, a menu link, that will always take you to the latest published node of that content type, but do it with a redirect, instead of a view with the latest node. The former says, when you go to this URL, redirect to the correct URL; while the latter says, when you go to this URL, display the content from that other URL here. Sometimes the latter is better, I prefer the former for my daily photos.
So, here's how you'd create that redirect in Drupal 7. You can put this into a page, or create a new module and add this to it, or use an existing module (say, a features
module or something).
<?php $query = new EntityFieldQuery(); $query ->entityCondition('entity_type', 'node') // of course, this would change to your node type ->propertyCondition('type', 'dailyphoto') // only published ones ->propertyCondition('status', 1) // 'posted' can also be 'created' if you prefer ->propertyOrderBy('posted', 'DESC'); $result = $query->execute(); if (isset($result['node'])) { // yup, ugly. Works. $nids = array_keys($result['node']); drupal_goto('node/' . $nids[0]); } else { // well shit, go home drupal_goto('/'); } ?>
Add new comment