For WordPress there are quite a few decent plugins to optimize images everytime you upload one ( I like EWWW ). But what about your old ones, and the ones that come via your theme and somebody forgot to do this?
Fortunately it’s quite easy to optimize images. These commands you can use to recursively batch process a whole directory structure. Just wait, and done.
find ./ -name '*.png' -print0 | xargs -0 optipng -clobber -preserve -nc -nb -o7
Optipng is for PNG images. Make sure it’s installed on your computer. The extra options are for preserving the permissions, overwriting and using quite some processing to come to the best optimization. You can alter the options.
If you want to use a different directory change the ./ (current) to something else.
For JPG’s :
find ./ -name '*.jpg' -print0 | xargs -0 jpegoptim -p -t -o