How to sort views summary on term weight programmatically

This is how you can sort your view on taxonomy term weight programmatically instead of using the default Summary, sorted ascending/descending

<?php
/*
* Hook views_pre_execute
*
*/
function mymodule_views_pre_execute(&$view) {
if (
$view->name == 'opportunity_summary' && $view->current_display == 'block_1') {
 
$search = array('ORDER BY term_data_name ASC');
 
$replace = array('ORDER BY term_data.weight ASC');
 
$view->build_info['query'] = str_replace($search, $replace, $view->build_info['query']);
 
$view->build_info['count_query'] = str_replace($search, $replace, $view->build_info['count_query']);
}


}
?>
Knowledge keywords: