How your dog gets worms can be dependent on the type of worm. Roundworms, Hookworms, and Whipworms can infect your dog when your dogs eats some eggs that are on the ground. For example if your dog eats some grass with eggs on, they can get worms.
A very happy dog rolling around on the grass in the sun
Dogs can get tapeworms by eating a flea that has eaten an egg. Heartworm, that live in your dog's heart and blood vessels, can be contracted from mosquito bites. Worms can be passed on to puppies if their mothers have them.