locate_template with multiple categories?

The code you posted is looping through all the categories that the post is assigned.

The foreach constructs a string representing every possible template file that it wants to check for and assigns them all to $template.

The locate_template() function will go through the $templates array and return the first one of them that actually exists. Thats what will be assigned to the $template variable.

If it turns out that none of the files exist, I believe locate_template() will return false. Your code there simply checks to see if locate_template() found any of the templates before assigning it to $template.

The whole function then returns the name of that template to the filter, which will load that template if you return an actual string, otherwise it will continue down the template hierarchy to the next type of template after ‘single’.

Edit: Additional information

get_the_terms uses wp_get_object_terms which by default will return the terms in ascending order by name so if a post is in multiple categories you will always be loading the template of the first term alphabetically. To change this behavior use wp_get_object_terms directly and specify the orderby arg to ‘count’, ‘slug’, ‘term_group’, ‘term_order’, or ‘term_id’.