Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress get_post_meta not working in loop

Tags:

php

wordpress

I am trying to get posts on a page ordered by custom field "price" I have done the ordering but now I cannot get the value of 'price' echoed. The get_post_meta does not give any output. Here is the code:

$args=array(
'meta_key'=>'price',
'post_type' => 'page',
  'orderby'=>'meta_value_num',
  'post_status' => 'publish',
  'posts_per_page' => -1,
  'caller_get_posts'=> 1

);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
 $count=0;
  while ($count<4 && $my_query->have_posts()) : $my_query->the_post(); ?>

    <td><a href="<?php the_permalink(); ?>">
    <img alt="product" src="/product-images/image.jpg" height="100px" width="75px"/>
    <p><?php the_title(); ?></p>
    <?php echo get_post_meta($my_query->ID, 'price', true); ?>
    </a>
    </td>
    <?php
    $count++;
  endwhile;
}
wp_reset_query();  // Restore global post data stomped by the_post().
?>
like image 727
Zeeshan Avatar asked Dec 25 '22 18:12

Zeeshan


1 Answers

You're trying to use a property on WP_Query ($ID) instead of the current post's ID. The first argument of get_post_meta should be a post ID, not a property of WP_Query.

If this is somewhere in a template you can do this:

<?php
while ($my_query->have_posts()) {
    $my_query->the_post();

    // use the global $post object
    echo get_post_meta($post->ID, 'price', true);
}

If it's no in a template file or somewhere that the global $post is declared, you can use get_the_ID instead:

<?php
while ($my_query->have_posts()) {
    $my_query->the_post();

    // use the global $post object
    echo get_post_meta(get_the_ID(), 'price', true);
}
like image 196
chrisguitarguy Avatar answered Jan 04 '23 18:01

chrisguitarguy