I am looking at adding an if/else statement, showing different HTML as required. My question is how I could possibly refine this code? Is there a more refined way of presenting this code?
<?php if ('Images' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Images</h1>
<div class="images">...</div>
<? } elseif ('Slideshow' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Slideshow</h1>
<div class="slideshow">...</div>
<? } elseif ('Video' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Video</h1>
<div class="video">...</div>
<? } elseif ('Audio' == get_post_meta($post->ID, 'project_type', true)) { ?>
<h1>Audio</h1>
<div class="audio">...</div>
<?php } ?>
Yes, this approach doesn’t take into account what might be happening within your
<div>
element. As this isn’t part of your question. If there is a lot going on I’d propose an object oriented approach. Another bad approach would be a switch statement.With OOP we can create something like the following:
Sometimes it can be cleaner to put all that markup in echo statements, but only if it is simple markup and the result is actually more readable than mixing in the php statements as above. Example:
Fleshgrinder is right, you could make this better by only using get_post_meta one time.
If the contents of the html is different for each of these, I would probably use a switch rather than else/elseif/etc…