I need to run a script at the end of each user session, and this seems like the best way to do it. I have no experience making X11 programs, so how exactly do I go about doing this?
The answer will depend on which display manager (if any) is used to start X. For example, if the Gnome desktop environment starts, then probably the Gnome Display Manager started X. If KDE, then the KDE Display Manager probably did it.
Once I knew which display manager is being used, I would consult the documentation for that specific display manager to see if it mentions a way to do what you want. Failing that, I would proceed along the lines described in your link -- but that involves knowing which "startup system" is being used. E.g., Ubuntu and Red Hat use Upstart; Arch Linux and Fedora use systemd; Debian (I think) uses SysV init.
The easiest solution by the way is to modify your system so that it boots into text mode, and conseqently for the user to get into the habit of using startx to start X. I do not know if that solution is acceptable, but this practice used to be fairly common in the mid-2000s (the last time I ran Linux) and earlier. Then you just call your script at the end of ~/.xinitrc. Well, it is slightly more complicated than that: the last line of that file is often of the form