How to fetch post id using the term id in WordPress

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-

<?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!


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.