WordPress.org

Ready to get started?Download WordPress

Forums

Show a custom field value(s) for a specific key, echo it and link it (4 posts)

  1. mariostella
    Member
    Posted 5 years ago #

    Hello, may be this is daily bread to a lot of you but I had to struggle to get this right, so I hope it will help some or at least one person out there.

    With the following piece of php you will be able to get the values assigned to a specific key, echo it and link it. I use it in my post pages to customize the navigation bar

    <?php
    $value = get_post_meta($post->ID, 'insert your $key here', true);
    if ($value=="your value here")
      echo "<a href='http://www.yourlink.com'>Hyperlink Text</a>";
    ?>

    TRUE returns the first value for your $key, false would return them all.

    If you would like to customize more posts depending on the value assigned to a common $key (say post1 and post2 have the same $key but different values for it) you may simply apply an elseif tag like this

    <?php
    $value = get_post_meta($post->ID, 'insert your $key here', true);
    if ($value=="your value here")
      echo "<a href='http://www.yourlink.com'>Hyperlink Text</a>";
    elseif($value=="your other value here")
      echo "<a href='http://www.yourlink.com'>Hyperlink Text</a>";
    ?>

    You may add as many elseif as you need

    That's it...hope it helps

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 5 years ago #

    While it's poorly documented at the moment, post_custom will do this somewhat simpler, if you're in The Loop.

    $value = post_custom('key');
    That gets all the custom values you have for that key on the current post. If there's only one of them, then it will be a string you can simply echo. If there's more than one, then it will be an array of strings that you can loop through with a foreach or similar.

  3. mariostella
    Member
    Posted 5 years ago #

    Thanks Otto, I will bear this in mind...I am just a total rookie with php so I truly appreciate a pro sparing a thought..actually if you don't mind I would appreciate a better explanation of what you wrote...maybe with a simple example..thanks!

  4. picard102
    Member
    Posted 5 years ago #

    I did something similar to display a list of links through custom fields. http://www.bloggingtips.com/2008/08/02/wordpress-custom-field-array/

Topic Closed

This topic has been closed to new replies.

About this Topic