WordPress theme files Organization

It seems like the WordPress community really loves this mix of PHP and HTML together, and as you say it often leads to very hard to understand and maintain code.

It is a common programming pattern to separate out ‘logic’ and ‘presentation’. Logic here is PHP code which makes decisions, presentation is HTML.

I strongly recommend trying to separate the two whenever you can, and put as much PHP in one place, and as much HTML in another place.

For example you might have:

<b>Your name: <?php if user_logged_in() { $name=get_user_name(); echo $name; }  else { echo "please log in!"; } ?></b>

To separate that out you could write:

<?php 
      if (user_logged_in()) {
            $name = get_user_name();
       } else { 
            $name = "please log in!";
       }
?>

<b>Your name: <?php echo $name ; ?></b>

This approach allows you to begin to move all your PHP and ‘business logic’ away from the HTML and the ‘presentation’ so that you can change the logic of the way things work separately from the way it’s presented.

I hope this helps! There are even more advanced solutions like PHP templating engines which do the separation even better, but maybe this is overkill.