1

I can get a list of node items by content type, using the following query:

$query = db_select('node', 'n');
    $query->condition('n.status', NODE_PUBLISHED);
    $query->condition('n.type', 'slider');
    $nids = $query
        ->fields('n', array('nid'))
        ->orderBy('changed', 'DESC')
        ->range(0, 4)
        ->addTag('node_access')
        ->execute()
        ->fetchCol();
    $nodes = node_load_multiple($nids);

I want to filter this output further with taxonomy. How can I do this?

1

You need to use the EntityFieldQuery instead of the SelectQuery that db_select uses. You should do something like this:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'slider', '=')
  ->fieldCondition('fieldname', 'tid', $tid)
  ->propertyOrderBy('changed', 'DESC')
  ->range(0, 4)
  ->addTag('node_access')
  ->execute();

The results will be an array of objects containing the nid and vid.

Read more about the fieldCondition

4
  • Sorry but i am a newbie in drupal. Can you add complete code to get the array of node items filtered with taxonomy? – Yalamber May 27 '11 at 19:24
  • @askkirati what you need to put in the fieldCondition depends on how you set up your field, it's name etc. – googletorp May 27 '11 at 19:42
  • What will i have to do if i have to get taxonomy named slider with term slider1 – Yalamber May 27 '11 at 19:45
  • @askk what matters is not what you named the vocabulary but what you named the field. Usually it will have a name of "field_..." – googletorp May 28 '11 at 6:47
0
$query = new EntityFieldQuery;

$entities = $query
  ->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', 'slider', '=')
  ->propertyCondition('status', NODE_PUBLISHED, '=')
  ->fieldCondition($field, 'tid', $tid, '=')
  ->propertyOrderBy('changed', 'DESC')
  ->range(0, 4)
  ->addTag('node_access')
  ->execute();

$nodes = entity_load('node', array_keys($entities['node']));

$field contains the name of the taxonomy term field; $tid is the taxonomy term ID for which the list of nodes is filtered.

3
  • what will be the value of $tid? – Yalamber May 27 '11 at 23:23
  • $tid contains the taxonomy term ID; if you need to filter the list of nodes basing on the vocabulary ID used for the nodes, then the query is slightly different. – kiamlaluno May 28 '11 at 0:17
  • This solution seems to work too. But i think both does the same thing – Yalamber May 28 '11 at 8:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.