1

I have an if statement that has some html and php in it. The way I have formatted it at them moment seems a bit messy:

EDIT

    <?php

         $audio_source = get_field( 'audio_source' );

         if ( $audio_source == 'From Url' ) {

             $audio = get_post_meta( $post->ID, 'audio_post_format_url', true );
             echo wp_oembed_get( $audio );

         } elseif ( $audio_source == 'From Library' ) {

             if ( !empty( get_field( 'audio_post_format_library' ) ) ) {
                 $audio = get_field( 'audio_post_format_library', $post->ID ); ?>
                 <audio controls class="audio-player">
                     <source src="<?php echo $audio['url']; ?>" type="audio/mpeg">
                 </audio>
              <?php
             }
         }
              ?>

Just wondering how I could make this cleaner in terms of readability and what is the most appropriate way to format this code. I know I should use the following approach when I have php and html together:

<?php if ( !empty( get_field( 'audio_post_format_library' ) ) ) : ?>
    <audio controls class="audio-player">
        <source src="<?php echo $audio['url']; ?>" type="audio/mpeg">
    </audio>
<?php endif; ?>

But on this specific case I am a bit confused on what to use.

3
  • Think about the purpose of the opening and closing PHP tags. These are for "escaping HTML". In a string of PHP statements, there is no reason to open and close, open and close, etc. From your elseif thru your nested if statement is all PHP. No need to <?php ?> again and again. It is also recommended to only use one syntax style but you are mixing the use of curly braces and the alt colon syntax.
    – jdm2112
    Jan 4, 2016 at 21:00
  • Makes perfect sense. Please have a look at my edit above to see if that's what you mean and if it is the best way to format it.
    – Madeirense
    Jan 4, 2016 at 21:13
  • Much cleaner. You might find this very helpful as well. make.wordpress.org/core/handbook/best-practices/…. Personally, I didn't realize the alt PHP syntax was taboo these days until I scanned this.
    – jdm2112
    Jan 4, 2016 at 21:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.