Only modify main loop. Use is_main_query() helper.

Use in_the_loop() to test to see if we're in the main loop or not. This
prevents this function from running in the <head> and such. Also use the
is_main_query() helper function instead of directly comparing $wp_query
to $wp_the_query.