With what I've heard from around the internet about the Ultra Beasts, connections with ORAS's Delta Episode, and further possibilities of a Pokemon multiverse, I have a theory of the story of how that's possible, which connects Sun and Moon's legends with those of the Generation VI games. Before I state it, I would like to point out that it makes sense in a way, since Generations VI and VII are on the 3DS and of course, with the 3DS specifics, you get the idea. Anyways, here's what I've pieced together, combined with some theories I have.
It starts 3,000 years ago as shown with X and Y, AZ, the king of Kalos, is forced to have his Floette participate in that big war. When Floette dies, AZ builds his ultimate weapon and captures Xerneas and Yveltal. First with Xerneas, he revives his Floette and the two are given immortal life, then using Yveltal's power, he uses it to kill all the people and Pokemon participating in the war, putting to an end. The blast from the ultimate weapon is so powerful, that it causes a rip in reality. The Original One, Arceus is disturbed by this rip, and summons Dialga, Palkia and Giratina to fix it. In doing so, they end up splitting the Pokemon world into five parallel dimensions. First is Dimension A, where the events of Pokemon Red, Gold, OmegaRuby and Y take place. Next is Dimension B, where Pokemon Blue, Silver, AlphaSapphire and X happen. Then, there's Dimension C, where Pokemon Yellow, Crystal, Emerald and Platinum happen. In Dimension D, Pokemon FireRed, HeartGold, Ruby and Pearl happen. Finally, there's Dimension E, where Pokemon LeafGreen, SoulSilver, Sapphire and Diamond happen. (I don't know where to insert Black and White 1 and 2 yet, so I'm gonna assume the Black games happened in Dimension A while the White games take place in Dimension B. Plus, I have a hunch that a Diamond remake set in Dimension B, and a Pearl remake set in Dimension A will happen.) In Dimensions A and B, the energy from the ultimate weapon causes Mega Evolution to come into existence, while in Dimensions C, D and E, history is rewritten so the war that caused all this in the first place never happened. Arceus, sensing this, creates the Ultra Beasts to protect each of the dimensions. The UB-02s (Buzzwole and Pheromosa) and the UB-04s (Kartana and Celestella) each guard a dimension together, while the remaining three (Nihilego, Xurkitree and Guzzlord) each guard a dimension alone. Arceus then creates the Cosmog evolutionary family, and grants the final evolved stages Solgaleo and Lunala the ability to travel across the dimensions using solar and lunar power respectively.
So that's my theory, and a big one at that. What do you'll think?