PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites

29 Dec 2015

Drupal 7 - Add custom fields to Search API solr index

     This is blog describes about how to add custom field to Search API solr index in Drupal 7.

     Suppose we need a new field, we can add new fields for a content type at /admin/structure/content/types. Then all fields are showed at /admin/config/search/search_api/index/default_node_index/fields. Now you can add desired fields to solr index.

     Suppose you want to show custom field to Search API results but that field is not created for any specific content types. Is it possible in Search API? Yes you can done this with use of hook_entity_property_info_alter().

/**
 * Implement phponwebsites_get_nodecountviews_nid()
 *
 * Return count of views by particular nid
 */
function phponwebsites_get_nodecountviews_nid($nid) {
  $result = db_query("SELECT COUNT(*) as count FROM {nodeviewcount} WHERE nid=:nid", array(':nid' => $nid))->FetchAssoc();
  return $result['count'];
}

/**
 * Implements hook_entity_property_info_alter().
 */
function phponwebsites_entity_property_info_alter(&$info) {
  $info['node']['properties']['is_nodeviewcount'] = array(
    'type' => 'integer',
    'label' => t('Node view count'),
    'description' => t("Number of views."),
    'sanitized' => TRUE,
    'getter callback' => 'phponwebsites_get_is_nodeviewcount_callback',
  );
}

/**
 * Implement phponwebsites_get_is_nodeviewcount_callback()
 */
function phponwebsites_get_is_nodeviewcount_callback($item) {
  $count = phponwebsites_get_nodecountviews_nid($item->nid);
  $total = (int) $count;
  return $total;
}

          After added above code into your custom module, go to /admin/config/search/search_api/index/default_node_index/fields. Now you could see new custom field is displayed as in below images.


Add custom fields to search API solr index in Drupal 7


         Now you can add your custom field into search api solr index and index that field. The custom field is listed in views add field section. Now you can add custom field into search results.