Skip to content

Instantly share code, notes, and snippets.

@daggerhart
Created February 9, 2017 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daggerhart/2189ba7bea03754044da20b1cb63de9c to your computer and use it in GitHub Desktop.
Save daggerhart/2189ba7bea03754044da20b1cb63de9c to your computer and use it in GitHub Desktop.
Example Drupal 7 input filter for inserting a node into an arbitrary formatted text field.
<?php
/**
* Implements hook_filter_info().
*
* @link https://api.drupal.org/api/drupal/modules%21filter%21filter.api.php/function/hook_filter_info/7.x
*/
function examplefilter_filter_info() {
$filters['examplefilter_node_embed'] = array(
'title' => 'EPI node embed',
'description' => 'Embed a node using its node id.',
'process callback' => '_examplefilter_node_filter_embed',
'tips callback' => '_examplefilter_node_filter_embed_tips',
);
return $filters;
}
/**
* Tips! Provide useful information to the content editing user about how to
* best use this filter.
*
* @param $filter
* @param $format
* @param bool|FALSE $long
*
* @return string
*/
function _examplefilter_node_filter_embed_tips($filter, $format, $long = FALSE){
return 'You can embed a node using the following snippet pattern. <code>[node nid=""]</code>';
}
/**
* Find any usage of this filter in a given block of text and replace it with
* the results desired. This example uses a callback to provide the node output.
*
* @param $text
* @param $filter
* @param $format
* @param $langcode
* @param $cache
* @param $cache_id
*
* @return mixed
*/
function _examplefilter_node_filter_embed($text, $filter, $format, $langcode, $cache, $cache_id){
$text = preg_replace_callback('|\[node nid="(.*)"\]|', '_examplefilter_node_filter_embed_replace', $text );
return $text;
}
/**
* Callback for preg_replace_callback that outputs a node if user has access
* to view it.
*
* @param $matches
*
* @return string
*/
function _examplefilter_node_filter_embed_replace( $matches ){
$nid = $matches[1];
$node = node_load($nid);
$output = '';
if (node_access('view', $node)){
$node_view = node_view($node);
$output = drupal_render($node_view);
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment