Global declaration for the variable was missing in the page. After adding the following declaration, code works as expected.
global $wp_query;
Global declaration for the variable was missing in the page. After adding the following declaration, code works as expected.
global $wp_query;