November 2012 Update: This issue was originally filed in 2009 to talk about porting Term Node Count to Drupal 7. After much discussion, no one took the lead, and we are now looking at a Drupal 8 release in less than a year. It would make more sense to develop for Drupal 8, however, a few people are wanting this module to handle counting large numbers of term nodes for current Drupal 7 sites. Although Views can inherently handle counting of a few thousand nodes, the process is too slow in Views for numbers higher than that. If anyone is interested in doing this, perhaps a new issue should be opened, since this one has so many unrelated support questions and old references.

Previous summary:
Someone just pointed me here from #602240: Re-add taxonomy_term_count_nodes(). Just a note that we completely removed taxonomy_term_count_nodes() from Drupal 7, which leaves modules relying on that function a choice between #603236: Add count facility to field_attach_query() or this module. In the interests of D7CX I'm opening this to start discussions about a D7 port.

Files: 
CommentFileSizeAuthor
#38 term_node_count.zip30.94 KBarshadcn

Comments

archard’s picture

It shouldn't be hard at all to port this to D7. Don't be surprised if there is a release from day 1.

catch’s picture

Cool. If any taxonomy changes look weird (there's a lot, like 80% of the module), just find me in irc.

Also consider tagging the project with d7cx if you're planning a prompt upgrade: http://cyrve.com/d7cx

Thanks :)

davidzz’s picture

Subscribing

CSCharabaruk’s picture

Subscribing -- D7 final seems pretty close, still looking to hit for launch day?

zorp’s picture

Subscribing

ranavaibhav’s picture

subscribing

jodam’s picture

Subscribing

boftx’s picture

subscribe

jodam’s picture

Assigned: Unassigned » jodam

my version for Drupal 7, code to module

$vid = 2;  // number of vocablurary
$pole = array();
$terms = taxonomy_get_tree($vid);
foreach ( $terms as $term ) {
 $count = db_query("SELECT COUNT(nid) FROM {taxonomy_index} WHERE tid = :aid", array(':aid' => $term->tid) )->fetchField();
  $pole[]=Array (l($term->name, "taxonomy/term/$term->tid") . " ($count)", $term->depth, $count, $term->tid)  ;
}
  foreach ($pole as $list) 
{
 
    echo "\n
  • $list[0]"; }
  • vitok-dupe’s picture

    subscribe

    a.siebel’s picture

    subscribe :-)

    picciuto’s picture

    @Jodam, where do you put that code? In a block?

    Barfly’s picture

    subscribe

    erdembey’s picture

    subscribe

    erdembey’s picture

    Title: Port to Drupal 7 » Port Term Node Count to Drupal 7

    Renaming for better tracking ...

    yugongtian’s picture

    +1

    dotist’s picture

    subscribe

    kenorb’s picture

    Title: Rework Term Node Count for D7 » Port Term Node Count to Drupal 7
    Assigned: Unassigned » jodam
    Status: Needs work » Active

    I'm not sure if there is sense to port this module to Drupal 7.
    You could simply achieve this functionality with Views 3.x it-self.

    Instruction for Drupal 6 (for Drupal 7, the naming could be different):
    1. Create Taxonomy Views.
    2. Add relationship to the node (in case if you want to count number of nodes).
    3. Enable grouping (Group by)
    (or "Use aggregation" toggle in D7, then set the "Aggregation Settings" for each field)
    4. In Style Settings/Format set Grouping field to 'Term ID' or 'Node ID' (depends of your query)
    5. Add new field 'Node: NID' and set Group type to: Count
    It depends what do you need. If you need to count nodes or terms.
    See: #1132368: How to display item/node count?

    The only thing that this module do, it keeping the static numbers of nodes in the table. Those numbers are not always refreshed (I had some differences), site is slowing down (by monitoring changes to terms), you can't count with filters (for specified content type), etc.

    With Views we have better flexibility, caching, filtering, sorting available, counting per type, etc.

    kenorb’s picture

    Status: Active » Closed (won't fix)
    dotist’s picture

    Fantastic!

    I had a feeling this would be possible w/ Views 3.x w/o any additional modules.

    Thanks for the explanation. In my case, i also wanted to filter out all terms w/ zero related content, which is easy once the grouping/relationship is established.

    One thing to note, in your number 4, i guess it's no longer called "Styles" but rather "Format".

    Thanks,
    Isaac

    kenorb’s picture

    I just found out, that step 4 is not necessary. It should work as well without setting Grouping field.
    I done it, because I'd some problem: #1145514: 'Grouping field' ignoring 'Exclude from display' settings when figuring out this functionality.

    OLD ACCOUNT USE ID 169175 INSTEAD’s picture

    How could this be changed to show a count of items with a certain taxonomy term? Say I have a page "/products/category/sub-category" and I wanted to show how many items have the sub-category term. This seems like it should be simple but I've messed with the Relationships options for hours now and can't get this working. Can you please explain step #2 in more detail, how to add this relationship? Thanks!

    kenorb’s picture

    @lrobeson:
    If you have node based view, you don't have to have relationship (probably). If you have Taxonomy based View, you should add:
    'Taxonomy: Node' (Get all nodes tagged with a term.)
    Then you have to count how many nodes per term you have which should be: COUNT(nid).
    If it doesn't work, please raise separate support ticket for Views, what you trying to achieve.

    Jerome F’s picture

    subscribe for further reading

    kevin-bcr’s picture

    To those participating in this thread:

    I would appreciate it if you could give a little more detail on the process above:

    1. Create Taxonomy Views.
    2. Add relationship to the node (in case if you want to count number of nodes).
    3. Enable grouping (Group by)
    4. Add new field 'Node: NID' and set Group type to: Count

    I currently have a Taxonomy I've created (Resource Types) and would like page or block views that show them in format, like:

    Charts (43)
    Maps (34)
    Timelines (15) ...

    Having created my taxonomy, what do you mean by "Create Taxonomy Views." The only place I can see where adding a relationship comes into play is if I create a Content Type. Anyway, I'm confused by what is meant by the first and second steps in the above process.

    Thank you!
    Kevin

    arshadcn’s picture

    Can anyone confirm if #18 works? If it does, I don't think we need to port this module to 7 and I'll add a note to the module page. Thanks

    klausi’s picture

    Title: Port Term Node Count to Drupal 7 » Document that this module is not necessary for D7
    Assigned: jodam » Unassigned
    Status: Closed (won't fix) » Active

    Yes, #18 works, thanks kenorb! So I also think a port is not necessary.

    Kami Petersen’s picture

    Status: Active » Closed (fixed)

    D7 instructions at #18 are linked to from the project page.

    rickumali’s picture

    I appreciated seeing this post, and the steps at #18 indeed work. The piece that was most confusing to me was Step 3 ("Enable grouping"). In Views, this is done by the "Use aggregation" toggle, under the Advanced menu on the main View page. Once you toggle this, you will have the ability to set the "Aggregation Settings" for each field.

    Mathijs Koenraadt’s picture

    I think the module's advantage was storing the counts in the database, for each node insert +1 or delete -1. The Views approach is not scalable beyond a few thousand items or so.

    klausi’s picture

    Views does caching, so this should not be a problem even for large data sets.

    andypost’s picture

    Status: Closed (fixed) » Active

    #18 is not clear about a trouble with that in some cases counts are not updated which seems strange.

    7.x branch contains usable code that could be used for upgrade path, also I'd like to note that sometimes it's a really useful to have a counter part of term. Suppose the module could introduce different kind of counters: per node-type and cumulative.

    Let's roll out 7.x dev version and I think this module could be useful and probably community will help to improve it

    Mathijs Koenraadt’s picture

    @#31 it does pose a problem! MySQL will crash if you try to count X million nodes. This is irrelevant to Views caching: it never gets cached because the server crashes. Think about MySQL max execution time, etc.

    The only stable solution is incremental counting, triggered by node insert/delete. So we still need the old module.

    Of course you can happily use Views 3 for small datasets. But it will eventually crash for large datasets or at least slow down your server.

    Even better is using MySQL innoDB triggers, but that's another story ;)

    xanderol’s picture

    I'm lost at step 3. How do I enable grouping?

    Edit: never mind I see the explanation at #29. Missed it the first read through.

    iancawthorne’s picture

    Hello, I'm quite confused by these instructions. I'm using term_node_count to sort a view in Drupal 6. Are these the steps to achieve this in Drupal 7?

    arshadcn’s picture

    You can use step above to do same in views 3. or use the Drupal 7 version of this module which comes with an example view exported. But see morningtime's comments on caching for large dataset.

    iancawthorne’s picture

    Where is the Drupal 7 version of this module? The project page does not have a module to download. There is information in the description for the module about Drupal 7 which just links to this thread. I can't see a example exported view on this thread?

    arshadcn’s picture

    FileSize
    30.94 KB

    My bad. I thought i added a release some time back ;) here's an export that should be a good starting point to build above in views.

    andypost’s picture

    For D7 seems more promising way to use votingapi + rules to calc any stats the site needs

    #38 has schema implementation but no updates are happen to update counters

    andypost’s picture

    Title: Document that this module is not necessary for D7 » Rework Term Node Count for D7
    Status: Active » Needs work

    taking into account #1007096: Port Views Content Cache to Drupal 7
    This is a only module which makes countable part of terms

    EDIT: having this project abandoned is bad idea as to make this with views

    quardz’s picture

    Title: Port Term Node Count to Drupal 7 » Rework Term Node Count for D7
    Component: Code » Documentation
    Assigned: jodam » Unassigned
    Status: Active » Needs work

    I succeed with Computed field in Drupal, but needs to save the terms often with bulk operation. Its a dirty way but works for me.

    1. Install Computed Field for D7
    2. Create a computer field to a vocabulary that you needs hold node count (Say : Node Count)
    3. Use the following code in PHP code area in computed field settings.
        $query = db_select('taxonomy_index', 'ti');
        $query->addExpression('COUNT(ti.nid)');
        $count = $query
          ->condition('ti.tid', $entity->tid)
          ->execute()->fetchCol();
      
        $entity_field[0]['value'] = $count[0];
    4. set : Data Type : int, Default value : 0
    5. Now the field will hold no of nodes associates with term
    6. create a taxonomy view and add the field 'Node Count' will avaliable as field as well as in sort and filter.

    Some Problem : You needs to create a bulk operation view and run to save the terms often, so the latest value will get updated.

    andypost’s picture

    Component: Documentation » Code

    Another issue with views approach - no ability to count a hierarchical taxonomies as original D6 taxonomy_term_count_nodes() does.
    Also views fails on large taxonomies so it makes sense to have this modules for D7

    alesr’s picture

    How to do it in Drupal 7 on Views 3:

    • Add new view
    • Show -> taxonomy terms
    • Continue
    • Relationships -> Taxonomy term: Content with term
    • Use aggregation:Yes
    • Taxonomy term: Name -> Group results together
    • Add field -> Content: Nid
    • Aggregation -> Count DISTINCT
    • Make your own style for Content: Nid field (Set prefix to "(" and suffix to ")" to get the count between brackets)
    techninja’s picture

    Not to beat a dead ticket, but how would the solution in #43 deal with unpublished nodes?

    EDIT: Turns out because it uses taxonomy_index, this is somewhat automatic. I'd say that's pretty well managed.

    unik’s picture

    #43 worked very good. Thanks alesr

    ressa’s picture

    NOTE: in #43, "Taxonomy term: Name -> Group results together" is done by setting "Grouping field" to "Taxonomy Term: Name" under "FORMAT: Format: Unformatted list | Settings". Click on "Settings" to do it.

    Jframe2002’s picture

    Hi Guys… #18 Worked perfect for me… quick question though… how can i get them to appear inline? any suggestions (i know this might be a stupid question, but I'm new to drupal.

    chaiwei’s picture

    #47, not sure if this helps, I am doing in this way

    1. Fields -> taxonomy term name -> exclude from display
    2. Fields -> Node: NID (Count) -> rewrite output -> below there is a placeholder list, check and put it as example [term_name]([nid])

    Then it will appear inline.

    sachbearbeiter’s picture

    worked perfectly - thanks a lot ...

    giorgio79’s picture

    #18 Step 2
    Created a taxonomy based view, but in relationships I do not have "node" only these

    " Taxonomy: Parent term
    The parent term of the term. This can produce duplicate entries if you are using a vocabulary that allows multiple parents.
    Taxonomy: Related terms
    The related terms of the term. This can produce duplicate entries if there is more than one related term."

    Weird.

    For the default taxonomy/term this is available

    "Taxonomy: Terms on node"

    adelka’s picture

    I have two vocabularies:
    1. cities (terms: new york, chicago....)
    2. food (terms: pizza, pasta, kebab....)

    I would like to create the block like this:

    if I go to /new-york page I will see count number for all of the relevant food, like:
    New York:
    pizza(200)
    pasta(350)

    for Chicago:
    pizza(100)
    pasta(50)

    etc.

    If no city selected, I would like to have number of all of the foods (this solution is proposed here and works).

    Any idea?

    kingdee40’s picture

    Term node count module error when installing:
    DatabaseSchemaObjectExistsException: Table term_node_count already exists. in DatabaseSchema->createTable() (line 652 of C:\wamp\www\site\includes\database\schema.inc).

    dgoldenbaum’s picture

    kenorb's #18 post was very helpful... I realized it might be helpful for folks to see the same explanation but with updated terminology for Drupal 7.

    1. Add a new view of type: taxonomy
    2. Add relationship: Taxonomy term: Content with term
    3. Other / Use aggregation = Yes
    4. Add new field: Content: NID, in the next pane, set aggregation type to count

    Anonymous’s picture

    Confirmed that #43 worked for me on Drupal 7 + Views 3. Thank you! I was pulling my hair out!

    I am using this as a block rather than a page and it still worked fine.

    MGParisi’s picture

    This is currently available with TagClouds http://drupal.org/project/tagclouds

    kenorb’s picture

    Status: Needs work » Closed (fixed)
    kenorb’s picture

    Status: Closed (fixed) » Postponed
    giorgio79’s picture

    Unfortunately Views cannot yet be used as php arrays.

    However, in D7 terms can have fields, so I am thinking of adding a node count (integer) field to terms, and writing some code that gets the node count.

    ghan’s picture

    Project: Term Node Count » Views
    Version: 6.x-1.3 » 7.x-3.3

    #53 is exactly what I've been looking for -- thanks dgoldenbaum and kenorb!

    j_nunes’s picture

    Isn't it possible to filter terms based on date field?
    The field doesn't allow relative dates with aggregation.
    I understand I must be having a date relationship.

    AndrzejG’s picture

    Issue tags: +taxonomy, +filter, +date

    #48 doesn't work for me. Rewrited [nid] field is still displayed as a record, not inline. I stripped all HTML tags, no success.

    srjosh’s picture

    #43 ftw! Thanks.

    ahhao’s picture

    #43 simple, clear, easy, and is WORKING!

    thank you very much.

    one more thing is very important to add on.

    Solution for #61 problem: Inline Taxonomy Name and [NID]

    Android (55)

    You must rearrange the [NID] to top of the [Taxonomy term: Name] in Fields

    after this, it should appear in REPLACEMENT PATTERNS if you have install Token module.

    AndrzejG’s picture

    Thanks, ahhao, but my problem seems different.

    I have:

    strategies (1)
    system (6)
    technology (5)

    and would like to have:

    strategies (1), system (6), technology (5),...

    j_nunes’s picture

    AndrzejG, did you manage to find how to do it?

    ahhao’s picture

    I didnt try it but this may solved the inline problem.

    refer to http://drupal.org/node/777840

    after this read this

    http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_lin...

    or

    can this solve by CSS?

    AndrzejG’s picture

    staminna - no, I didn't.

    As to coding solutions - sorry I perceive this kind of approach as nonsense, and a straight way to clutter Drupal (it is cluttered enough).

    -----
    Is it difficult to quip Views with "Inline list", to complement HTML list, Grid, Table etc.? Such list could be useful not only for tags, but also to list Titles, Users, Authors etc.

    dawehner’s picture

    Wouldn't it be some html list with a different css or do you want to have comma-seperatered values?

    AndrzejG’s picture

    I think first option (HTML) would be the best, since it could keep the possibility to display items as links to some content (basically to the listing Page, as tags do).

    AndrzejG’s picture

    Hm, I think the best solution would be similar to the display of multivalue fields, as we can type in the custom separator. In this way we can have various displays, for example Tags, Bloggers, cities of events, and much more.
    In order to avoid misunderstanding, a note should be added that this format is only for displaying one or two fields...

    fishfang’s picture

    I don't know if I can solve my problem with this solution.
    I want to display under each node the terms of that node and - for each term - the count, how often this term is used overall. Somethings like this:

    Node 1
    Term A (3) Term B(2)

    Node 2
    Term A (3) Term B (2)

    Node 3
    Term A (3) Term C (1)

    I'm not sure if I can use one of these solutions?

    macjules’s picture

    couturier’s picture

    Shouldn't we be applying any effort on this to 8.x-dev?

    dawehner’s picture

    It is amazing how much work you do in the queues, especially in the last hours!

    This issue is so full of different support questions, old discussion in term node count etc. so if there is something to do
    we should create a new one, which a clear summary.

    Actually i don't really see what views should do.

    couturier’s picture

    Status: Postponed » Closed (won't fix)

    I agree this issue can be closed. I have been working to find a solution for another problem, dawehner, which is why I am closing these issues cluttering the active queue. Usually I am not in here as much because I am not a programmer, but I am happy for people like you who are. Thanks for all your good work!

    andypost’s picture

    Project: Views » Term Node Count
    Version: 7.x-3.3 » 6.x-1.3
    Issue tags: -taxonomy, -filter, -date

    If nobody care to add a countable part for taxonomy term let's live this issue in original issue queue

    Mathijs Koenraadt’s picture

    I still prefer a D7 module that actually saves the count in a database table, instead of on-the-fly counting for each page-load. It's much better for performance.

    kenorb’s picture

    @morningtime: Views are supporting caching, you can choose for how long you want to cache the content, instead of using SQL queries. In the other hand both solutions are using SQL queries and using Views the count is calculated by SQL (which has caching as well), so it should be very fast.

    yultyyev’s picture

    Counting nodes with terms works fine with Drupal 7, but how can I add some enhancements to this?

    I need to count nodes with terms (e.g. category) with extra argument (e.g. city). Simple counting works fine, when there is no nodes marked with some term, it's shows zeros in term list (myterm1: 0). But when I added a new contextual filter (another relation: node taxonomy field term, contextual filter: "term=city": show all if empty), it works not pretty much. When the argument is empty - it works like it should, but when I set some argument, empty terms items are hiding from term list. I tried to check sql result, and it really return only terms with > 0 nodes when argument is set, and all terms when argument is empty - I just removed "where term='london'", LEFT JOINs may stay there)

    icylace’s picture

    What about #33? Views caching seems irrelevant in the face of the database crashing before anything can get cached.

    couturier’s picture

    icylace, are you using Drupal 7? This issue is filed under D6. If you are still having problems, please open a new issue with your details. Also, make sure your hosting plan supports D7 with Views. You will need plenty of php memory and other server resources.

    icylace’s picture

    @couturier So, you're saying that #33 does not apply to Drupal 7 + Views 3? If so, then that's great to hear.

    couturier’s picture

    @icylace If I remember correctly, Views caching in D6 was poor and supposedly improved in D7. There is still work to be done which will further improve Views caching in D8 (Views is in core in D8), but the severity of the problems in #33 should be repeated in more current issues if other people are still experiencing them in D7. #33 was posted in 2011, and most sites have transisted to D7 since then. So yes, I believe that comment referred to D6. Please open a new issue and let us know what you are experiencing. You can link your new issue with a reference here, if you wish.

    icylace’s picture

    @couturier It's good to know that D7 views caching has improved but I believe that #33 brought up an issue that had nothing to do with views caching. To quote #33: "MySQL will crash if you try to count X million nodes. This is irrelevant to Views caching" If I'm not mistaken, Term Node Count avoided this issue therefore a D7 version of it would be very useful. I have not experienced any problems yet since I'm in the process of researching what modules I'd like to use for the site I'm building.

    couturier’s picture

    @icylace if your site is new, then you should be developing in Drupal 7, and Term Node Count is not a module in D7, just a View configuration. Export a View from this reference: http://drupal.org/node/603868#comment-4421144

    icylace’s picture

    @couturier I appreciate your effort to help and I will of course use Drupal 7 but my concern, as mentioned in #33, is with the way MySQL would be used. How does the comment you reference, #18, deal with this?

    couturier’s picture

    This is an edited record of emails that @icylace and I exchanged in response to the previous post that may be helpful to someone else looking for a Drupal 7 module to handle counts of data sets larger than a few thousand.

    couturier:

    Hi, I just wanted to send you a private message, since the Term Node Count issue is closed and has a lot of followers already. You cannot use the Term Node Count module for Drupal 7 development, because it doesn't exist. The last version was for Drupal 6. For Drupal 7 and beyond, you can configure Views to do the same thing without the use of an extra module. The link I referenced has an exported View already configured to do that.

    icylace:

    I appreciate you private messaging me and my apologies for not realizing the issue was already closed. I understand that Term Node Count doesn't have a Drupal 7 version. I'm aware that Views nowadays can do a similar thing by itself. However, http://drupal.org/node/603868#comment-5052372 implied that Term Node Count did incremental counting to avoid possible MySQL slowdowns and/or crashes once counting gets too big. It also stated that this issue is irrelevant to Views caching. The solution you originally proposed http://drupal.org/node/603868#comment-4421144 does not seem to say how Views handles this particular case if at all. I would very much like to know the answer to this.

    couturier:

    I think I understand now what you wanted to know. So, you have data sets larger than several thousand? Yes, that might be a problem using Views for caching because it will be too slow to work well. I am really not qualified to give you technical advice for this module. It appears that someone suggested updating Term Node Count to Drupal 7 to handle very large numbers. Also, you'll see someone talked about "MySQL innoDB triggers," so that might be an alternate way. No one has taken time to update Term Node Count to Drupal 7 yet, but if you are interested, maybe you can find someone to work with you to become a maintainer for the module and keep it going. You might also keep looking for other modules that do something similar for Drupal 7.

    icylace:

    Thank you for your response. I will keep an eye out for similar modules. Depending on how my current project goes I may be able to contribute some effort towards making a D7 version of Term Node Count.

    Conclusion:
    Does anyone else have a need to revive the Term Node Count module for Drupal 7, or do you know of another module that will do the same thing?

    Anandyrh’s picture

    I am not sure of any other module doing this, I am not a code writer, but I have my D6 site running and large number of taxonomies are being used. Now I am trying to upgrade my site to D7 but all my taxonomy pages were dependent on Term node count module. So now, after reading these above responds, I have decided to wait for this excellent module to be ported to D7.

    Bright Web Design’s picture

    Dear All,

    I have created a how to tutorial for all those who are having trouble creating this taxonomy count using views aggregator. Please checkout the tutorial from here.
    http://www.brightwebsitedesign.com/how-to-use-views-aggregator-to-create... if you are having trouble or need any assistance just leave a comment I will get back to you with some tips.

    Best Wishes.

    Andreyy’s picture

    This solution doesn't count parent term nodes.
    For example, wrong tree is:
    - Drupal (0)
    -- Drupal 7.1 (2)
    -- Drupal 7.2 (2)
    -- Drupal 7.3 (2)

    Right tree is:

    - Drupal (6)
    -- Drupal 7.1 (2)
    -- Drupal 7.2 (2)
    -- Drupal 7.3 (2)

    Does anybody know how to count nodes for the parent term?

    JoachimF’s picture

    Status: Closed (won't fix) » Active

    I'm building a classified advert area on my site - I want to display terms with the number of nodes associated with each term in a list.

    I've set my View up as instructed in https://drupal.org/node/603868#comment-5197322

    This works fine but I'd also like to display taxonomy terms where there is no content (0) eg:

    • Bicycles (0)
    • DVD (4)
    • Musical instruments (2)
    • Phones (0)
    JoachimF’s picture

    Issue summary: View changes

    Update

    chrisck’s picture

    Issue summary: View changes
    Status: Active » Closed (won't fix)

    edit: duplicate post

    chrisck’s picture

    JoachimF, there are at least 3 sets of instructions on how to do exactly what you want on this page. What I think you are missing is that you need to create a view that shows Taxonomy terms, not Nodes. This is done during the creation of your view.