WordPress.org

Ready to get started?Download WordPress

Forums

get_post_meta display (3 posts)

  1. damian.smith
    Member
    Posted 1 year ago #

    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.

  2. Justin
    Member
    Posted 1 year ago #

    <?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

  3. damian.smith
    Member
    Posted 1 year ago #

    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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.