0

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

    <?php
    // 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
        ", 
        $meta_key
    ) );
    echo "<p>Total views {$views}</p>";
    ?> 

    <?php endwhile; ?>
1
  • 1
    your query is missing the post id
    – Milo
    Commented Dec 2, 2011 at 2:43

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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