WordPress.org

Ready to get started?Download WordPress

Forums

Custom Fields to Add Links (6 posts)

  1. bongkph
    Member
    Posted 3 years ago #

    Hi, Right now I want to display 3 links on my article using custom fields. Here is what I did:

    <div>
    <h3>Related Top Searched</h3>
    <ul>
    <li><?php
    { $gsubtitle = get_post_meta
    ($post->ID, 'gsubtitle', $single = true);
    if($gsubtitle !== '') echo $gsubtitle;} ?></li>
    
    <li><?php
    { $bsubtitle = get_post_meta
    ($post->ID, 'bsubtitle', $single = true);
    elseif($bsubtitle !== '') echo $bsubtitle;} ?></li>
    
    <li><?php
    { $ysubtitle = get_post_meta
    ($post->ID, 'ysubtitle', $single = true);
    if($ysubtitle !== '') echo $ysubtitle;} ?></li>
    </ul>
    </div>

    It serves the purpose but the only problem is that it shows even on posts that dont have the value. Like:

    Related Top Searched
    > (blank)
    > (blank)
    > (blank)

    What I want to do?
    I want to show this 3 custom fields only if they have a value. I know contidional tags can do it but I dont know how to apply. Also please help me make the code simple. Thanks a lot.

  2. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    try and restructure your code:

    <?php
    $gsubtitle = get_post_meta($post->ID, 'gsubtitle', $single = true);
    $bsubtitle = get_post_meta($post->ID, 'bsubtitle', $single = true);
    $ysubtitle = get_post_meta($post->ID, 'ysubtitle', $single = true);
    
    if( $gsubtitle || $bsubtitle || $ysubtitle ) : ?>
    
    <div>
    <h3>Related Top Searched</h3>
    <ul>
    <?php
    if($gsubtitle !== '') echo '<li>' . $gsubtitle .'</li>';
    if($bsubtitle !== '') echo '<li>' . $bsubtitle .'</li>';
    if($ysubtitle !== '') echo '<li>' . $ysubtitle .'</li>';
    ?>
    </ul>
    </div>
    <?php endif; ?>

    (this is assuming that you want all filled in custom fields to show)
    if the elseif on the $bsubtitle is important, the re-integrate it into the second line of the ifs.

  3. bongkph
    Member
    Posted 3 years ago #

    alchymyth, thank you very much for the code. It works.

  4. alchymyth
    The Sweeper & Moderator
    Posted 3 years ago #

    you are welcome.
    glad that i could help ;-)

  5. bongkph
    Member
    Posted 3 years ago #

    alchymyth, one more thing, how do I make the links to open in new window?

  6. bongkph
    Member
    Posted 3 years ago #

    On another website I use it but only one custom field. But this time I want the result link to be like:

    <a target="_blank" href="http://www.website.com/">View Source</a>

    Where "http://www.website.com" is the value of the custom field.

Topic Closed

This topic has been closed to new replies.

About this Topic