Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a wordpress query for a custom post type, but I want to filter the results depending on the value of a custom meta.

    <?php $my_query = new WP_Query('post_type=prizes&showposts=3&orderby=rand');
while ($my_query->have_posts()) : $my_query->the_post(); 
$do_not_duplicate = $post->ID; $my_meta = get_post_meta($post->ID,'_my_meta',TRUE); ?>

<?php if(($calctotalnew - number_format($cart->total,2)) >= $my_meta['pointsvalue']){ ?>

    <div class="footerprizecontainer">
        <a href="<?php the_permalink();?>"><span class="footerprizetitle"><?php the_title();?></span></a>

        <div class="footerprizevalue">
            <h2><?php echo $my_meta['pointsvalue'];?></h2>
        </div>

        <div align="center">
            <a href="<?php the_permalink();?>"><?php the_post_thumbnail('thumb');?></a>
        </div>

    </div>

<?php } 

Thats my code. Bascially the IF statement in the loop filters the results, but I need them filtering as they are queried because it doesnt always show exactly 3 posts (as some posts will have a value above what if filtered in the IF statement.

Any thoughts?

Thanks

share|improve this question

1 Answer 1

up vote 2 down vote accepted

This is super easy to do with meta_querys:

$args = array(
    //basics
    'post_type'      => 'prizes',   // from question
    'post_status'    => 'publish',  // you didn't have this, but it's good practice
    'posts_per_page' => 3,           // I don't know where you got 'showposts', but that's WAY old

    //order
    'orderby'        => 'rand',

    //meta query
    'meta_query'     => array(
        array(
            'key'     => $my_meta['pointsvalue'],
            'value'   => ( $calctotalnew - number_format( $cart->total, 2 ) ),
            'compare' => '<=',
            'type'    => 'NUMERIC'
        )
    )
);

$my_query = new WP_Query( $args );

Also, your $do_not_duplicate is completely non-sensical. It's setup but never called, you probably want to address that.

I filled in some of the details for you, they may not be right. The documentation on WP_Query will help you get everything correct.

share|improve this answer

Your Answer

 
discard

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.