For the different type of operation, we need to filter the default loop in WordPress. Sometimes we need to get post ID from a specific term ID(tag, category). In this tutorial, I will show you how to get post ID by category/tag ID.
The useful function is given in bellow-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php /* * Returns post IDs in a term with a given ID * * @param int $term_id(Category ID, Tag ID) * * @return array|int Post ID(s) */ function get_post_id_by_term_id( $term_id ){ global $wpdb ; $ids = $wpdb ->get_col( $wpdb ->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d" , $term_id ) ); if ( count ( $ids ) > 1 ) return $ids ; // return array else return $ids [0]; // return int } ?> |
Here we have used
$wpdb
global object of wpdb class which contains a set of functions used to interact with a database.
In fact, using
$wpdb
you can get IDs of posts by any parameter — category name, publish date, number of comments, even by comment author email etc.
🙂 happy coding!

Previous Article
How to set perfect product image sizes in WooCommerce
Next Article