1

I'm trying to get the below 3 columns for all posts that are in my database

  1. user_name
  2. post_title
  3. pods_field_blog_category

user_name and post_title is stored in wp_posts table pods_field_blog_category is stored in wp_postmeta table.

below code displays, user_id and post_title , but I'm not sure how to get the meta_value and display it:

<?php
$posts = get_posts(array(
    'posts_per_page' => -1,
    'post_type' => 'custom_post'
        )
);

if ($posts):
    ?>
    <ul>
        <?php
        foreach ($posts as $post):

            setup_postdata($post);
            ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                //what should be the code to display the meta value pods_field_blog_category
            </li>
        <?php endforeach; ?>

    </ul>

    <?php wp_reset_postdata(); ?>

<?php endif; ?>
Jacob
  • 2,212
  • 1
  • 12
  • 18
jeez
  • 33
  • 5

1 Answers1

1

get_post_meta() methord is used to get postmeta.

You can use it like this:

$key_1_value = get_post_meta($post->ID, 'pods_field_blog_category', true);

UPDATED
If you want to retrieve multiple postmeta then then you can use any of the following method:

Method 1:

$key_1_value = get_post_meta($post->ID, 'key_1', true);
$key_2_value = get_post_meta($post->ID, 'key_2', true);

Method 2: (recommended)

$key_value = array();
$meta = get_post_meta($post->ID);
foreach ($meta as $key => $value)
{
    $key_value[$key] = $value[0];
}
print_r($key_value);

Method 3: as said my @daniel in the comment

$keysArray = array('key_1', 'key_2', 'key_3');
foreach ($keysArray as $key)
{
    $key_value = get_post_meta($post->ID, $key, true);
}

Hope this helps!

Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97
  • Thank you , it works. if i have multiplefields how can i get it ? the above retrieves just one field . suppose i have additional field , should i hardcode everytime the above line of code . cant this get_post_meta($post->ID ==> and asssign output1=field1 , output2=input2 meta input fields ?? – jeez Jan 16 '17 at 05:21
  • 1
    You can create an array of the custom 'fields' and then loop through each value. E.g. `$examples = array('field1', 'field2', 'field3'); foreach ($examples as $example){echo get_post_meta($post->ID, $example, true);}` – Daniel Jan 16 '17 at 06:19
  • Raunak , thanks print_r($key_value); displays results in continues way of array ..example field1,field2 ..how do i get this value and assign to seperate variable . example var1= $key_value(field1), var2=$keyvalue(field2) – jeez Jan 17 '17 at 05:23
  • @jeez: for 2nd and 3rd method you can use it in this way: `$var1 = $key_value['field1'];` `$var2 = $key_value['field2'];`. – Raunak Gupta Jan 17 '17 at 07:12
  • Cheers @jeez. Don't forget to accept my and answer and up-vote it. :) – Raunak Gupta Jan 19 '17 at 18:23