WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This is giving the same views value for each post how would I grab the next var for each post?

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    // set the meta_key to the appropriate custom field meta key
    $meta_key = 'views';
    $views = $wpdb->get_var( $wpdb->prepare( 
            SELECT meta_value
            FROM $wpdb->postmeta 
            WHERE meta_key = %s
    ) );
    echo "<p>Total views {$views}</p>";

    <?php endwhile; ?>
share|improve this question
your query is missing the post id – Milo Dec 2 '11 at 2:43

Instead of querying the database directly you could use the following code instead.

printf( '<p>Total views : %s</p>', get_post_meta( get_the_ID(), 'views', true ) );
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.