This is not a well understood behaviour. It seems it may be an evolutionary hangover of a way of sharing a novel smell with the pack or disguising your own scent.
We still do not fully understand this behaviour, but there seem to be two main schools of thought on the subject: one suggests it is a hangover from their wolf ancestors; the other that the scent may serve to camouflage their own.
Scent is crucially important in the societies of many mammals, dogs in particular. A great deal of valuable information can be shared about an animal through the scent it leaves behind, including its species, age, sex, health and reproductive status. Let’s say a wolf leaves its pack and ventures off on its own to forage or explore a territory and, on its travels, it comes across a novel smell; fox poo, for example. The best way to share this 'interesting' smell with the other members of its pack is to roll in the substance from which the smell is emanating. In this instance, the explorer rolls in the fox poo, and the smell is carried back on its fur. When it returns to its pack, the other wolves greet it by sniffing it and will readily detect this novel scent.
Some canine behaviourists consider that a domestic dog rolling in droppings may be a hangover of this “scent sharing” behaviour. It is noteworthy, however, that there seems something unique about fox poo that attracts dogs. My dogs, for example, have only shown an inclination to roll in fox droppings; ignoring the poo of other animals, such as cows, deer and other domestic dogs. It may be that larger canids are more interested in other predator odours, which smell more strongly than herbivore droppings, particularly those that might be either competitors or looking to scavenge from their kills.
Another theory is that by rubbing themselves in the scent of some other animal, they can mask their own scent and thus are better camouflaged from potential predators or prey. There is a considerable amount of evidence suggesting that prey items respond to the odours of their predators, so masking your odour with that of something else makes sense while you’re out hunting. It also makes sense that deer are more likely to run if they catch the scent of a wolf than a fox.
Recently, a team led by Max Allen at the University of Wisconsin at Madison observed gray foxes (Urocyon cinereoargenteus) living in the Californian mountains deliberately rubbing themselves in the scent marks left by mountain lions (Puma concolor). In a paper to the Journal of Ethology in January 2017, Allen and his colleagues suggest that the foxes may use this puma scent to disguise their own, making them less easy for coyotes, their main predators in California, to track them down.
The jury is still out, but the scent communication hypothesis would seem to fit better in the case of domestic dogs.