Support

Account

Home Forums General Issues If custom select field = "" Reply To: If custom select field = ""

  • Hi Jason,

    I actually think you can make this a lot easier on yourself.
    Instead of having three queries (inside an empty and completely unnecessary loop) you can probably do a single query and order the results based on your meta data. Luckily in the alphabet it goes L – M – S 😉

    Here’s a very refactored code I think should do the trick for you (you might need to set the order parameter too). I haven’t tested this live.

    
    <section id="content">
    	<section id="featured">
    		<div class="row">
    		
    			<?php 
    			// args
    			$args = array(
    				'post_type' => 'post',
    				'meta_key' => 'homepage_size',
    				'orderby' => 'meta_value',
    			);
    			 
    			 // query
    			$the_query = new WP_Query( $args );
    			
    			?>
    
    			<?php if( $the_query->have_posts() ): ?>
    				<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
    					
    					<?php 
    					$size = get_field('homepage_size');
    					$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
    					$image_style = ( $image ? "background-image: url('" . $image[0] . ");" : '' );
    					
    					if( $size === 'large' ){
    						$classes = 'col-md-6 col-sm-6 col-xs-12 post featured-' . $size;
    					}else if( $size === 'medium' ){
    						$classes = 'col-md-6 col-sm-6 col-xs-12 post featured-' . $size;
    					}else{
    						$classes = 'col-md-3 col-sm-3 col-xs-12 post featured-' . $size;
    					}
    					
    					?>
    		
    					<div class="<?php echo $classes; ?>" style="<?php echo $image_style; ?>">
    						<div class="post-content">
    							<div class="category">
    								<?php $categories = get_the_category(); foreach($categories as $category) { $cat_name = $category->name; if($cat_name != 'featured') echo '<a href="'.get_category_link($category->term_id).'">'.$cat_name . '</a> '; } ?>
    							</div>
    							
    							<div class="clearfix"></div>
    					
    							<header class="title">
    								<a href="<?php the_permalink(); ?>">
    									<h1><?php the_title(); ?></h1>
    									<h2><?php the_field('subtitle'); ?></h2>
    								</a>
    							</header>
    						</div>
    					</div>
    					
    				<?php endwhile; ?>
    			<?php endif; ?>
    			<?php wp_reset_postdata();	 // Restore global post data stomped by the_post(). ?>
    		</div>
    	</section>
    </section>