When you discover some new feature that you've never seen before on StackOverflow (or elsewhere) I suggest you take some time to read the documentation, which often contains examples.
In this case you seem to have discovered:
user-defined functions
pl/pgsql language functions
triggers
There is lots of excellent material and examples on how these things all work in the documentation.