Query Posts or Get Posts by custom fields, possible?

The question:

If I were to take a standard query post.

<?php query_posts('post_type=payment'); while (have_posts()) : the_post();?>

Only this time I would like to query the post by 2 custom fields that it may contain.

<?php query_posts('post_type=payment'.get_post_meta($post->ID,'bookingref', true).get_post_meta($post->ID,'customerref', true) ); while (have_posts()) : the_post(); ?>

That doesn’t work. Is something like this possible and how is it done?

Any ideas?

Marvellous

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

To query posts by custom fields you can use the ‘meta_query’ parameter

<?php
$args = array(
'post_type' => 'payment',
'meta_query' => array(
        array(
            'key' => 'bookingref',
            'value' => 'the_value_you_want',
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'customerref',
            'value' => 'the_value_you_want',
            'compare' => 'LIKE'
        )
);
query_posts($args); while (have_posts()) : the_post(); ?>

you can’t use get_post_meta inside the query because it gets you the value and not the key and also it accepts a Post ID to get that value of and before the query $post->id is not in the scope.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment