I'm looking to display the following loop, only if a custom field data exists, if not, I don't want to display anything.

 <?php while (have_posts()) : the_post(); $data = get_post_meta( $post->ID, 'key', true );?>
  <!-- info --> 
<?php endwhile; ?>

Any guessing?

Thanks in advanced.


If you want to avoid preprocessing the data, this will work (though it's definitely the quick and dirty method):

<?php while (have_posts()) : the_post(); ?>
    <?php $data = get_post_meta( $post->ID, 'key', true ); ?>
    <?php if( $data != '' ) : ?>
        <!-- info --> 
    <?php endif; ?>
<?php endwhile; ?>

Otherwise (and this is definitely the better way to go if you need the best functionality), you can do a preliminary loop through the data (or even get different data using the meta), determine if any of the posts have meta, then conditionally execute the loop.

  • 1
    That will interfere in the post count, and can also make navigation and other stuff look weird. – vmassuchetto Jan 22 '12 at 12:36

You can change the query_posts behavior without even changing a template file.

function custom_query($request) {
    $params = array(
        'meta_key' => 'custom_field_name',
        'meta_value' => 'custom_field_value'
    return array_merge($request, $params);
add_filter('request', 'custom_query');
  • You solution does not take into account whether or not it is the primary query, but I agree that preprocessing, not conditionals, are the way to go. I've edited my answer to reflect as such. – mor7ifer Jan 22 '12 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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