Creating list of similar nodes in Drupal 7/Views 3

Stanislav Kniazev picture Stanislav Kniazev · May 4, 2012 · Viewed 21.4k times · Source

Copy from drupal.stackexchange.com hoping to get more answers here:

I face a rather common problem of displaying a list of nodes similar to current one. Similar node is defined as one having at least one taxonomy term that current node has. There are few solutions available as modules, however the modules I've found (specifically Similar By Terms) are in beta stage (as in "not working properly") for Drupal 7.

I've also found a couple of solutions based on Views and contextual filters (such as http://scito.ch/content/show-related-nodes-block-based-taxonomy-terms-views-3-and-drupal-7) or relations. I quite like this way as it saves me installing extra modules and with Views being actively developed and supported I'd prefer to use them rather than any custom solution. The problem I can't get around is how to sort "similar nodes" by the number of terms they share. For example, if I have "IPhone 4S" Node with Terms "Gadget", "Apple", and "Phone", I want similar nodes in the following order:

  1. IPhone 3 (Apple, Gadget, Phone)
  2. IPad (Apple, Gadget, Tablet)
  3. Mac (Apple, Computer)
  4. Bramley (Apple, Fruit, Tree)

How can I sort nodes in this view by the number of terms they share?

This question is about building a view, please do not suggest module or custom php-based solutions. Thank you.

Answer

nmc picture nmc · Jul 6, 2012
  1. Create a block view
  2. Add Contextual filter -> Content: Nid -> Provide default value -> Content ID from URL
  3. Add Relationship -> Content: Taxonomy terms on node -> specify the appropriate vocabulary
  4. Add Relationship -> Taxonomy term: Content using vocabulary as specified above -> Check off Require this relationship
  5. Turn on Views aggregation (NOTE: the arrow in the screenshot below is pointing to the wrong spot and should be pointing to 2 rows below where it is)
  6. Assuming you are listing title only, edit the title field to use the Relationship you set up in #4 above.
  7. Add new sort criteria of Content: Nid. In aggregation settings, select Count. Use relationship from #4 and sort descending
  8. Add Contextual filter -> Content: Nid -> Use relationship from #4 -> Provide default value - Content ID from URL -> Scroll down and expand "More" then check "Exclude" to remove current node from the view

** See comment by @garret-albright below for testing this in the Views UI preview. **

Related node view