The first thing which needs to be done is that the child needs to see a pediatrician who specializes in encopresis, or a pediatric gastroenterologist. Once a child past the age of 4 starts soiling their pants, it might be a medical problem. (There are medical conditions that start earlier, but they are usually recognized as such.)
This can start insidiously with just constipation then a painful BM. The painful BM makes the child afraid to go again, which results in their holding it in, having a harder stool, maybe larger, and again painful, so it becomes a self-reinforcing problem.
Boston's Children's Hospital describes it like this:
How does encopresis happen?
Constipated children have fewer bowel movements than normal, and their bowel movements can be hard, dry, difficult to pass and so large that they can often even block up the toilet. Here are some examples why:
-Your child's stool can become impacted (packed into her rectum and large intestine).
-Her rectum and intestine become enlarged due to the retained stool.
-Eventually, her rectum and intestine have problems sensing the presence of stool, and the anal sphincter (the muscle at the end of the digestive tract that helps hold stool in) becomes dilated, losing its strength.
-Stool can start to leak around the impacted stool, soiling your child's clothing.
-As more and more stool collects, your child will be less and less able to hold it in, leading to accidents. Because of decreased sensitivity in your child’s rectum due to its larger size, she may not even be aware she’s had an accident until after it has occurred.
This is why "I don't know" is the most common answer parents get when they ask their child, "Why didn't you tell me you needed to go?" The colon and sphincter do not give them the signals they need to feel to evacuate 'properly'.
The approach initially will be medical: a dietary change, a bowel evacuation, laxatives, liquids, fiber, etc. With luck (it's still early), your child will respond and this will be a thing of the past.
Often, however, the treatment of longer episodes of encopresis require a multidiciplinary approach: doctor, dietician, and therapist.
Read reputable sites on encopresis. Many parents have gone through this; there are even online encopresis support groups you can join. Good luck!