What are some best practices for customizing the loop in WordPress using PHP?

When customizing the loop in WordPress using PHP, it's important to follow best practices to ensure your code is efficient and maintainable. One common approach is to use the pre_get_posts action hook to modify the query parameters before the loop is executed. This allows you to customize the loop without directly modifying the main query.

function custom_query( $query ) {
    if ( $query->is_main_query() && $query->is_home() ) {
        $query->set( 'posts_per_page', 5 );
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'DESC' );
    }
}
add_action( 'pre_get_posts', 'custom_query' );