Site icon Dhanendran's Blog

Goodbye `get_terms`, Welcome `WP_Term_Query`

From WordPress 4.6, we have a new class called ​WP_Term_Query which will help us in querying the taxonomies easily.

This class will give us more flexibility and ease of use like other classes like WP_Query,WP_User_Query, and WP_Comment_Query in WordPress. The main benefit is the caching and security measures. So you don’t need to write complex and insecure SQL queries.

Sample Code:

$term_query = new WP_Term_Query( $args );
if ( ! empty( $term_query->terms ) ) {
    foreach ( $term_query->terms as $term ) {
        echo $term->name;
    }
} else {
    echo 'No term found.';
}

We can pass custom query parameters via $args array.

Parameters:

Sample Code:

$term_query = new WP_Term_Query( array( 'taxonomy' => 'category' ) );
if ( ! empty( $term_query->terms ) ) {
    foreach ( $term_query->terms as $term ) {
        echo $term->name;
    }
} else {
    echo 'No term found.';
}

 

Exit mobile version