Search code examples
wordpresshidedisplaymeta-boxes

Hide html if metabox is empty, using custom post types


I am trying to only show the #firstimg if the metabox is filled, because else it just displays an empty box because it's searching for an image that isn't there.

I am using Custom Post Types and I can get the images to show so far, but as soon as I try to hide the #firstimg all it does is mess up my code (it does not display the rest of the website, and there is nothing in my console log either so I have no clue what I'm doing wrong).

I'm assuming I might be close (hopefully?) but that I didn't write the code correctly. Hopefully someone is willing to help me out!

  <img class="port-img" id="firstimg" src="
  <?php $key_1_value = get_post_meta($post->ID, 'ecpt_img_1', true); 
    if( ! empty( $key_1_value ) ) { 
    echo $key_1_value; 
    document.getElementById("firstimg").style.display = "block";}
  ?>">
  <img class="port-img" id="secondimg" src="<?php $key_2_value = get_post_meta($post->ID, 'ecpt_img_2', true); if( ! empty( $key_2_value ) ) { echo $key_2_value;}?>">
  <img class="port-img" id="thirdimg" src="<?php $key_3_value = get_post_meta($post->ID, 'ecpt_img_3', true); if( ! empty( $key_3_value ) ) { echo $key_3_value;}?>">

Solution

  • You're not escaping or echoing your JavaScript, which is what's causing the site to fail to load past that point (you're getting a Fatal Error).

    Why don't you just prevent displaying the image at all if the key doesn't exist, something like this:

    $key_1_value = get_post_meta( $post->ID, 'ecpt_img_1', true );
    $key_2_value = get_post_meta( $post->ID, 'ecpt_img_2', true );
    $key_3_value = get_post_meta( $post->ID, 'ecpt_img_3', true );
    
    if( $key_1_value ) echo '<img class="port-img" id="firstimage" src="'. $key_1_value .'" />';
    if( $key_2_value ) echo '<img class="port-img" id="secondimage" src="'. $key_2_value .'" />';
    if( $key_3_value ) echo '<img class="port-img" id="thirdimage" src="'. $key_3_value .'" />';
    

    Or better yet you could even just loop through 1, 2, and 3 as an array (note that you'd have to change your CSS from #firstmage to #image-1, etc - but it really simplifies things. You also don't need to define the key variable and then check it later, because get_post_meta() will return a truthy value, or false if it doesn't exist, so you can compare it at the same time you define it:

    foreach( range(1,3) as $i ){
        if( $image_src = get_post_meta( $post->ID, "ecpt_img_$i", true ) ){
            echo "<img class='port-image' id='image-$i' src='$image_src' />";
        }
    }