My daughter does this too every once in a while. She'll be so good about pooping in the potty and then randomly go in her pants for a while. She's 4 and I don't think kids this age always know how their bowels work.
One of my sons had the same problem after potty training early on. Please read up on encopresis. I googled like yourself asking other moms for help and found someone with almost an identical story. We also implemented a dairy free and more important gluten free diet also adding a fish oil supplement. This was suggested by a holistic nutritionist. This has changed his and our lives after trying stool softeners, suggestions of a child psychologist etc. Insist your ped. xray his/her abdomen and go from there. But I strongly add that his Ped. put him on a stool softener for 8 months and it did NOT solve the problem. His colon had stretched as well as had a blockage. Over time with his changed diet he now can again feel when he needs to go and has very few accidents. Also, he understands that is isn't and wasn't his fault but that he had a bad tummy. Best of luck and health to you all.
I haven't but one thing that comes to mind is if he is busy and "involved" he may ignore the signal to head to the bathroom until it is too late. Another common cause is that he may be slightly constipated and used to "having" to go without going and then the signals get confused as to when to actually go.
I'd start reminding him around the time he usually goes (one of mine is like clock work and the other is whenever which is harder to do that with). But even if you have to remind him frequently, maybe it will spur him into hitting the toilet for the big event. good luck (oh, and don't punish him for it. A child of 5 does not enjoy soiling himself.)