Filter posts by custom fields wp_query

This tutorial I am explaining how to filter posts by custom fields using wp_query. Using wordpress meta_query() parameter we can retrieve the post based on the custom field.

Here I am filtering the post based on the category name and the custom field ‘front_page’ checkbox. Then displaying those filtered posts as blocks in the home page.Please refer the image below.I have created a custom field checkbox and filtering the post based on that from the database.

filter post by custom fields wp_query

  1. Filter post by custom field
  2. Display filtered posts

Filter post based on custom field wp_query

In this example I have created custom fields ‘front_page‘ checkbox and retrieve the post based on that using wp_query. Based on that checkbox values and the category ‘courses‘ I need display the post on the home page.For that I am filtering the data from the database using the following query (wp_query).Here I am also sorting the filtered post based on the sort attribute.
[‘orderby’ => ‘menu_order’,’order’=>’ASC’,]

$args = array(
        'category_name' => 'courses',
        'orderby'       => 'menu_order',
        'order'         => 'ASC',
        'meta_query' => array(
                'key'     => 'front_page',
                'value'   => 'yes',
                'compare' => 'LIKE',


$the_query = new WP_Query( $args );

Display Custom Post

The above query will select all the post belongs to the course category and the front_page checkbox checked. For displaying the post on the homepage please loop through the result as shown below.

<?php if( $the_query->have_posts() ): ?>
            <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
                            $heading = get_field('front_page_heading',$post->ID); 
                            echo substr( $heading, 0, 15 ).'..';                                
                    <h4 ><?php echo get_field('sub_heading',$post->ID); ?></h4>
                    <?php if( $image ) : ?>
                       <img src="<?php echo $image['sizes']['blog-img']; ?>" alt="<?php echo $image['alt']; ?>" class="img-responsive" />
                    <?php endif; ?>
            <?php endif; endwhile; ?>

<?php endif; ?>

<?php wp_reset_query();     ?>

Please leave a reply if you have any further queries.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *