Custom query to get terms from post ids

I want to get the terms object by given posts ids. I don’t know much about sql, and this kinda complicated for me. Here is what i tried:

global $wpdb;
$taxonomy = 'category'
$term= $wpdb->prefix.'terms';
$relations= $wpdb->prefix.'term_relationships';
$taxo = $wpdb->prefix.'term_taxonomy';
$sql = "SELECT $term.*, $relations.*, $taxo.* 
            FROM $term
                JOIN $relations 
                    ON $term.term_id = '$taxo.term_id'
                JOIN $taxo 
                    ON $relations.term_taxonomy_id = $taxo.term_taxonomy_id
            WHERE $taxo.taxonomy = '$taxonomy' AND $relations.object_id IN (116,118) 
            GROUP BY $term.term_id";
$values = $wpdb->get_results($sql, ARRAY_A);

Don’t know what is wrong. It just don’t work.

1 Answer
1

It is not advised to make use of custom SQL queries if there are functions in WordPress that already does the job.

To accomplish this, you can simply make use of wp_get_object_terms(). The first parameter $object_ids takes a string or an array of object ID’s. In your case, you can make use of an array of your post ID’s. This will retrieve all the terms assosiated with the given post/s.

Here is an example

$terms = wp_get_object_terms( array(394,530),  'category' );
if ( ! empty( $terms ) ) {
    if ( ! is_wp_error( $terms ) ) {
        foreach( $terms as $term ) {
            ?><pre><?php var_dump($term); ?></pre><?php 
        }
    }
}

This will give you the following output

object(stdClass)#494 (10) {
  ["term_id"]=>
  int(115)
  ["name"]=>
  string(8) "child-01"
  ["slug"]=>
  string(7) "child01"
  ["term_group"]=>
  int(0)
  ["term_taxonomy_id"]=>
  int(115)
  ["taxonomy"]=>
  string(8) "category"
  ["description"]=>
  string(0) ""
  ["parent"]=>
  int(21)
  ["count"]=>
  int(2)
  ["filter"]=>
  string(3) "raw"
}

Leave a Comment