ttmt
ttmt

Reputation: 4984

get_post_meta in WP_Query

I'm doing a plugin to add likes to posts

I want to create a table on a page in the plugin to show each post and the number of likes

function my_plugin_options() {

    echo '<p>Table of Likes</p>';
    echo '</div>';

    echo '<table>';
  echo '<tr>';
  echo '<td>Post</td>';
  echo '<td>Number of likes</td>';
  echo '</tr>';

    $like_args = array(
        'post_type' => 'post',
        'order' => 'DES',
        'post_status' => 'publish'
    );

    $like_loop = new WP_Query($like_args);

    if($like_loop->have_posts()):
        while($like_loop->have_posts()):
            $like_loop->the_post();

    $likes = get_post_meta( $like_loop->post_ID, "_like_amount", true);     

    echo '<tr>';
    echo '<td>';
    the_title();
    echo '</td>';
    echo '<td>';
    $likes;
    echo '</td>';
    echo '</tr>';

    endwhile;
    endif;

    wp_reset_postdata();

    echo '</table>';
}

I have a meta field in each post '_like_amount' that is the number of likes.

How do I use this meta field in my WP_Query.

I've tried

$likes = get_post_meta( $like_loop->post_ID, "_like_amount", true);

Upvotes: 0

Views: 3100

Answers (1)

Moishy
Moishy

Reputation: 3648

try adding add global $post;

then $post->ID

in your case

if($like_loop->have_posts()):
        while($like_loop->have_posts()):
            $like_loop->the_post(); global $post;

Then

$likes = get_post_meta( $post->ID, "_like_amount", true);

Upvotes: 3

Related Questions