jeez
jeez

Reputation: 33

Display wp_post and wp_postmeta

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

Upvotes: 1

Views: 1378

Answers (1)

Raunak Gupta
Raunak Gupta

Reputation: 10809

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!

Upvotes: 1

Related Questions