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'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.

share|improve this question

2 Answers 2

up vote 0 down vote accepted

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.

share|improve this answer
    
perfect, thanks a lot –  andresmijares25 Jan 22 '12 at 2:35
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');
share|improve this answer
    
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. –  m0r7if3r Jan 22 '12 at 13:51

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.