I'd like to be able to count the number of nodes of a specific content type, declare the result as a global variable and then use that within the body of any other node as plain text within, for example, any paragraph. (Ideally, I'd like to twin that with a second global variable drawn from the most recent content post date for the same content type, probably using the same approach.)

Any suggestions?

Accepted answer

Hi,

That's a lot to go on, argiepiano, and is potentially very helpful. Many thanks indeed.

Comments

Hello trapeharde32. I'd create a custom token to output that global variable, use the module token filter to be able to include tokens in text fields, and insert the token in the desired node fields.

Hello argiepiano. Thank you. It's not clear to me how to populate that global variable in the first instance. Any pointers on that, please?

Hi!  In fact a global variable may not be necessary.

I would create a custom module that implements two hooks: hook_token_info_alter(&$data) to define the token itself, and hook_tokens() to fulfill the values. You probably want to add this new token within the 'site' token type (that's done in hook_token_info_alter()).

So, then, inside your hook_tokens() implementation you will put the code that will do the node counting. You may use a static variable there to avoid re-counting every time the hook is fulfilled within the same page request, but that's optional.

The counting of nodes could be done with a database query, like:

$query = db_select('node');
$query->condition('type', $my_type);
$count = $query->countQuery()->execute()->fetchField();

Then you would return that count in your implementation of hook_tokens() as an associative array - see documentation for hook_tokens. 

Good resources:

  • General info about hooks.
  • Custom tokens example provided by the module Examples for Developers
  • Devel module, which allows you to test code snippets while you develop and to debug code by outputting variables etc.  

Hi,

That's a lot to go on, argiepiano, and is potentially very helpful. Many thanks indeed.