Modifying a view with hook_views_query_alter

If you ever find yourself in a situation where you need to manually change the some parameters in a view then hook_views_query_alter() is your answer.

I had a situation where I had a view of CTA links. These links consisted of a title/image and link to the content. These displayed a the bottom of the article content types. Each CTA had a path to a specific article. The problem was that I didn't want the same link to display on the article that was current. So to do this I used hook_views_query_alter().

 

Ok first thing in you view you do have to add in a condition for this field. Not really sure why, but otherwise it doesn't seem to display anything. Make it something like where the link url contains '/'. They always will so there is no issue where nothing will display.

Secondly in your custom module you need to do 2 things, create a file called CUSTOMMODULE.views.inc in your root folder.

in your CUSTOMMODULE.module add this function 

 

function CUSTOMMODULE_views_api() {

return array( 'api' => 3.0, );

}

This just allows the module to use the views api.

Now in your CUSTOMMODULE.views.inc you can write your hook

function CUSTOMMODULE_views_query_alter(&$view, &$query) {

if ($view->name == 'random_ctas') {

$article = arg(2, drupal_get_path_alias());

$where = array();

$where['conditions'] = array();

$where['conditions'][] = array(

'field' => 'field_data_field_content_link.field_content_link_url',

'value' => '%' . $article . '%',

'operator' => 'NOT LIKE',

);

$where['args'] = array();

$where['type'] = '';

$query->where[] = $where; }

So all I did was pull the argument of the url and match that against the link in the content type. Don't show it if it matches

Add new comment