A dog can get stuck with his head in fences, buckets and trash cans because of the crest of his head, called the occiput. The narrow muzzle of many breeds allows them to push their heads into interesting places, but their ears and occiput hinder their ability to back out.
The occiput is a protuberance on the occipital bone and varies in size depending on the breed. The occipital bone forms the back of the skull and meets with the neck. Depending on the size of the occiput and the type of ears the dog has, he can easily get stuck when trying to back his head out of a narrow space.
In many breeds, a dog's head is flatter from top to bottom than it is from side to side, so tilting his head to the side would allow him to back out when he is stuck. Sometimes, through a lot of struggling, a dog manages to do exactly that and free himself.
Dogs can use their vibrissae, or whiskers, to help measure the size of a space. Each vibrissa maps to a specific part of a dog's brain, to give him highly detailed information about what size and type of object might be near his face. Ideally, this information would stop a dog from sticking his face into a narrow opening, but a dog's enthusiasm for what might lie in the bottom could override the sensory information being provided by the vibrissae until it's too late.
Dogs also get stuck together while mating, which has nothing to do with the occiput, ears or vibrissae. A male dog's penis swells during mating so he and the female are stuck together for as much as half an hour. This is called a tie. The male dog can pivot himself so he is tail-to-tail with the female during the tie, as opposed to being stuck mounted on her, but the dogs remain stuck like that until the swelling reduces.