0

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

1 Answer 1

2

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.

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.