Views API advance

/**
 * Add filters programmatically.
 */
function modulename_views_page() {
  $display_id = 'viewname-block_3';
  $nodeblock = array($display_id);
  $block = block_load('views', 'viewname-block_3');
  $block->subject = "";
  $views = views_get_view ('viewname');
  $views->set_display('block_3');
  $views->set_arguments(array('nid')); 
  if (!empty($_GET['delta'])) {
    $views->add_item('block_3', 'filter', 'field_data_field_fieldname', 'delta', array('value' => array('value' => $_GET['delta']), 'operator' => '=','relationship' => 'none', 'group_type' => 'group','group' => 1 ));
  }
 
  if ($_GET['color']) {  //filter taxonomy
    $views->add_item('block', 'filter', 'field_data_field_color', 'field_color_tid', array('relationship' => 'field_product_product_id', 'value' => $color));
  }
  //order by price
  $views->add_item('block_3', 'sort', 'field_data_commerce_price', 'commerce_price_amount', array('relationship' => 'field_product_product_id', 'order' => 'asc'));
  $views->set_current_page($_GET['page']); //set page number
  $views->pre_execute();
  $block = $views->display_handler->execute();
  $views->post_execute();
  views_add_block_contextual_links($block, $views, 'block'); //add views contextual link
  $nodeblock[$display_id] = $block['content'];
  $nodeblock[$display_id]['#block'] = $block;
  $nodeblock[$display_id]['#theme_wrappers'] = array('block');
  $nodeblock['#sort'] = TRUE;
  $nodeblock = drupal_render($nodeblock); //theme as block
  $output = $nodeblock;
  return $output;
}
 
/**
 * Add filters programmatically.
 */
function modulename_views_query_alter(&$view, &$query) {
  if ($view->base_table == 'node' && $view->name == 'views_display_id_here') {
    $join = new views_join();
    $join->table = 'field_data_field_dummy';
    $join->field = 'entity_id';
    $join->left_table = 'node';
    $join->left_field = 'nid';
    $join->type = 'left';
    $query->add_relationship('field_data_field_dummy', $join, 'field_data_field_dummy');
    $query->where[$c]['conditions'][] = array(
        'field' => 'field_data_field_dummy.field_field_dummy_value',
        'value' => '1234',
        'operator' => '=',
        );
    $query->where[$c]['conditions'][] = array(
        'field' => 'field_data_field_dummy.field_data_field_dummy_value',
        'value' => '',
        'operator' => 'is null'
        );
    $query->where[$c]['type'] = 'OR';
    $query->where[$c]['args'] = array();
  }
}
Help Share this Article