What best practices should be followed when implementing a category filter in WordPress using PHP?

When implementing a category filter in WordPress using PHP, it is best practice to first check if the category parameter is set in the URL and then use it to filter the posts accordingly. This can be done by modifying the main query using the pre_get_posts hook and setting the category parameter based on the URL value.

function custom_category_filter( $query ) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ( is_category() ) {
            $category = get_query_var( 'category_name' );
            if ( $category ) {
                $query->set( 'category_name', $category );
            }
        }
    }
}
add_action( 'pre_get_posts', 'custom_category_filter' );