Wp Query

In this lecture, We are talking about WP_Query. As we know wp_query is pre-defined class of wordpress, and we use it in different kinds of parentheses and parentheses. There are two things in wp_query which are “Type of Request” and “The Loop”. In wp_quey we request the database to get posts and we print those posts by using worpress standard get post loop.

WP_Query mostly uses to get specific types of data from databases. Like specific categories, tags, and author posts.

Category Parameters
The below code is for displaying posts by category id:

$query = new WP_Query( 
        array( 
            'cat' => 4 
        )
);

 

The below code is for displaying posts by category slug:

$query = new WP_Query( 
    array( 
        'category_name' => 'blog' 
        ) 
);

 

Tag Parameters
The below code is for displaying posts by tag slug:

$the_query = new WP_Query( 
    array( 
        'tag' => 'blog' 
        ) 
);

 

The below code is for displaying posts by tag id:

$the_query = new WP_Query( 
    array( 
        'tag_id' => 13  
        ) 
);

 

Custom Taxonomy Query
The below code is for displaying posts of custom taxonomy like First Aid Kit, Under Equipment taxonomy.

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'equipment',
            'field'    => 'slug',
            'terms'    => 'first-aid-kit',
        ),
    ),
);
$the_query = new WP_Query( $args );

 

After getting post data from the database by using wp_query in $the_query variable. Now it’s time to display posts by using standard loop.

<?php
// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
while ( $the_query->have_posts() ) {
    $the_query->the_post();
    echo '<li>' . get_the_title() . '</li>';
}
    echo '</ul>';
} else {
    echo '0 Posts Found';
}
/* Restore original Post Data */
wp_reset_postdata();
?>

 

Query with Cards
Here is the code of wp_query with bootstrap card which we are following in our custom wordpress theme course.

<?php if( $the_query->have_posts( ) ): while( $the_query->have_posts() ): $the_query->the_post( ); ?>
<div class="col-md-4">

    <div class="card">
        <?php if(has_post_thumbnail()) : ?>
            <img src="<?php the_post_thumbnail_url(); ?>" class="card-img-top" alt="<?php the_post_thumbnail_caption(); ?>">
        <?php endif; ?>
        <div class="card-body">
            <h5 class="card-title"><?php the_title(); ?></h5>
            <p class="card-text"><?php the_excerpt( ); ?></p>
            <a href="<?php the_permalink( ); ?>" class="btn btn-primary">Explore More</a>
        </div>
    </div>

</div>
<?php 
    endwhile; else: echo '0 Posts Found!';   endif; 
    wp_reset_postdata();
?>

 

#BeingCodeStuffing

Related Theme Developments