How to speed up a wordpress function with multiple loops?

I would just retrieve an array of alphabet/taxonomy terms that have posts. You do this, but doesn’t actually use it. This function will return an array of non-empty (alphabet) terms:

(Transient? – unless you have multiple post types using this taxonomy, (see below) I’m not sure if much is gained from using transients – and you can just call to get_terms and use wp_list_pluck as shown). The following function uses transients.

 wpse50148_get_used_alpha(){

     if ( false === ( $alphabet = get_transient( 'bam_archive_alphabet' ) ) ) {
            //It wasn't there, so regenerate the data and save the transient
            $terms = get_terms('alfa');
            $alphabet =array();
            if($terms){
                $alphabet = wp_list_pluck($terms,'slug');
            }
            set_transient( 'bam_archive_alphabet', $alphabet );
        } 

      return $alphabet;
 }

Don’t forget to update the transient when a post is updated.

This method assumes that the only post type using this taxonomy is ‘artistas’ – if it is being shared then a letter may claim to have artistas associated with it (in your menu) when it does not.

Shared taxonomy work-around

To get round this, you would have to query the posts and then loop through them and collect their terms. Either way – only 1, not 26 queries are being performed to get the ‘used’ alphabet. A transient would be more obviously time-saving in this scenario.

Usage:

  $alphabet = wpse50148_get_used_alpha();

   foreach(range('a', 'z') as $i) : 
      if( in_array($i,$alphabet) ){
           //Letter has terms
      }else{
           //Letter does not have terms
      }
   endif;