• I have this code:

    [ Moderator Note: Please post code or markup snippets between backticks or use the code button. ]

    <?php
    global $product, $woocommerce_loop;
    $related_cats = get_post_meta($post->ID,'related_cat', true);
    $related_cats = explode('|',$related_cats);
    foreach ( $related_cats as $related_cat) {
    echo '<div class="image-cat">
    <a href="/?product_cat='.$related_cat.'"><img src="/wp-content/uploads/'.$related_cat.'.jpeg" alt="Related Cat1" width="200" height="200" /></a>
    
    <p><a href="/?product_cat='.$related_cat.'">'.$related_cat = str_replace("-", " ",$related_cat).'</a></p>
    </div>';
    }
    ?>

    But if there is no $related_Cat then it still displays the div and blank image etc.

    I cant figure out how to re write this to only show the echo’d content if it actually exists.

Viewing 2 replies - 1 through 2 (of 2 total)
  • <?php
    global $product, $woocommerce_loop;
    $related_cats = get_post_meta($post->ID,'related_cat', true);
    if($related_cats != ''){
    $related_cats = explode('|',$related_cats);
    foreach ( $related_cats as $related_cat) {
    echo '<div class="image-cat">
    <a href="/?product_cat='.$related_cat.'"><img src="/wp-content/uploads/'.$related_cat.'.jpeg" alt="Related Cat1" width="200" height="200" /></a>
    
    <p><a href="/?product_cat='.$related_cat.'">'.$related_cat = str_replace("-", " ",$related_cat).'</a></p>
    </div>';
    }
    }
    ?>

    Try that.. you just have to check before continuing with the echo

    Thread Starter damian.smith

    (@damiansmith)

    I had to make some tweaks to your code to get it working:

    <?php
    global $post;
    
    $related_cats = get_post_meta($post->ID,'related_cat', true);
    $related_cats = explode('|',$related_cats);
    
    foreach ( $related_cats as $related_cat) {
    
    if($related_cat != NULL){
    
    echo '<div class="image-cat">
    <a href="/?product_cat='.$related_cat.'"><img src="/wp-content/uploads/'.$related_cat.'.jpeg" alt="Related Cat1" width="200" height="200" /></a>
    
    <p><a href="/?product_cat='.$related_cat.'">'.$related_cat = str_replace("-", " ",$related_cat).'</a></p>
    </div>';
    
    }
    
    }
    ?>

    [Please post code & markup between backticks or use the code button. Your posted code may now have been permanently damaged by the forum’s parser.]

    But now works perfectly! Thanks for the help

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘get_post_meta display’ is closed to new replies.