So far, I've been using the PHP filter in most of my websites. After reading Top 15 Drupal performance tips, where it says "What makes it worse is that when the PHP filter module is used, none of the code executed gets cached. So please, put all of your code into custom modules."

I was wondering how I can put some php code in a module to be used in certain ways I've been using it so far. For example:

  1. When I want to show the current year in the footer and I use the function
    echo date('Y');
    
  2. When I insert a link in a node and I use a php code like
    global $base_url; echo $base_url.'/'.drupal_get_path_alias('node/5212');
    

So ok, I can move that to functions in a module, but I still would need to insert php code to call those functions, wouldn't I?. So, I'm a bit lost on this question.

Can anybody give some help about how to do this properly?.

Comments

nevets’s picture

One approach would be to use tokens and modules like Token Insert and Token Insert Entity

Three approaches with a custom module are to implement blocks, input filters and/or custom tokens.

Another approach that works with templates is to add a preprocessor for the template (for example hook_preprocess_page()) and add a custom variable that can be printed in the template. See Setting up variables for use in a template (preprocess and process functions)

taote’s picture

Thank you for you quick reply. I will investigate what you comment.

Just one question, what do you mean in your second paragraph with input filter as an approach with a custom module?

nevets’s picture

When you edit content and blocks you will see a link "Text format", with values like "Filter HTML" and "Full HTML". Modules can implement custom text format (aka input filters), for example there formatters for inserting views and another for inserting blocks (I think there is also one for inserting nodes).

jaypan’s picture

It depends on what you are building for your pages. The above suggestions are good if you are speaking of simple little bits of PHP code, but if you need anything more complex, you are best off looking at how to build Drupal modules, and building your pages using a module.

Contact me to contract me for D7 -> D10/11 migrations.

taote’s picture

I have another situation, where there is a view with two fields, and depending on who is viewing it I need to show field1 or field2. So the only way I've thought to get this is using a third field of type php using the module https://drupal.org/project/views_php.

Is it ok to use PHP in this way?. Will it affect to the performance of the website?.

Can anyone think of a differente way of selecting the field to show without using this module?.