First we have to game out how Spain could keep Mexico in the first place. It might be easier than Britain hanging on to the North American colonies, perhaps--I am certainly not educated enough on Mexican or general Latin American history to speak with any confidence about how hard or easy it might have been for Spain to hang on to any of it. OTL they certainly hung on to Cuba for most of the century.
So I'd need you or someone to say how.
As I do understand it, a big part of the revolutionizing and secession of most of Latin America in the early 19th century was the interruption of Spanish power by the Napoleonic Wars. Basically Napoleon conquered Spain, and thus the Royal Navy stood between Napoleon's version of the Spanish government and the Americas. They did not blockade Napoleon with perfect success of course; he operated a lot in the Caribbean, intervening in Haiti, and I don't know what all else. Nappy was a factor in the Western Hemisphere, therefore we can't attribute to the RN the absolute power to shut him down on the high seas. But the British certainly did impede him a lot! Clearly then even if he had made retaining all of Spain's possessions a high priority, despite his commanding position on the European Continent, overseas he was in a dangerously weak place.
Well, now, didn't the British have a refugee and hence more or less puppet Spanish claimant of their own to support? Why not Britain assisting their candidate for the Spanish throne retaining all of Spain's claims, thus moving those colonies over to the asset side of the British accounts, presumably even after the war when a victorious Coalition might mean Spain is now effectively a British client?
As I understand it, the British apparently figured it was six of one or half a dozen of the other, whether the Spanish colonies continued to be united under a king on their side or broke up into a bunch of independent republics; either way British domination of trade would give Britain a good deal of influence. In fact one might suggest the British were clearly better off without the Spanish Empire of the Indies existing on paper--as long as the unified structure did exist, a Spanish king who gained strength (and where more likely from than the American colonies?) would be able to shift his alliance, turn on British interests, either favor some other strong sea power or attempt to develop Spanish trade at the expense of all foreigners--and if we assume he'd be strong enough to keep the colonies in hand, he'd have all of them together supporting him. Whereas if the Spanish empire dissolved in a wave of permanent secessions, each relatively small republic (or duchy, kingdom, empire, whatever) would be the more at British mercy and so, via divide and rule, Britain is better off, while Spain becomes a non-factor on any large, serious scale.
Upshot--with Spain herself a plaything between more powerful European powers, it is hardly reasonable to expect any help to those who attempted to rule in Spain's name back in America, unless it came from one non-Spanish hegemon or the other. I suppose if Napoleon could spare the power he'd have needed to project across the Atlantic, he'd have just annexed the Spanish possessions to France directly. Dead end for your OP that way! Britain could have tried annexing them the British crown, but they'd have a hard time holding them, what with the religious conflicts between the Church of England (which the British monarch is head of) and Catholicism. (This would have been less of a problem for Napoleon of course--he got along fine with the Papacy, largely because he had it at bayonet point, partially from having been born and raised a Catholic himself; his nation was, depending on which phase of recent history we look at, either Catholic, or atheist. The atheists were not totally banned but were out of style; at some point Napoleon had the Pope crown him Emperor). I'd have thought therefore they'd uphold a puppet Spanish monarchy instead, but apparently not, and I've given some reasons why they might not bother.
So what you need first of all is to either sweep away the dynamic that left Spain helpless to maintain control over the colonies on her own hook, or bring in some ATL second power with an interest in preserving the Spanish claims and the central structure.
But having Spain cut off by being conquered meant even more problems than just not being able to send in necessary forces, but the political impact in the colonies of the king being thus humiliated. A certain portion of his control over the colonies had to stem from awe of his power, implying it is best not to cross the king whereas if pleased he can reward you. Take that away and at least some people are going to shake their heads and reason that if Spain is not strong enough to protect them, they had better look to themselves. Add to this another stratum that may have had active, even bitter resentments against Spanish rule; these being restrained before by fear of Spanish power now are loose, having everything to lose if Spain comes back and much to gain if she doesn't.
Then there is the question of whether Spanish power hadn't been declining for quite some time anyway, even before Napoleon came along to demonstrate it. I have the impression this was certainly the case all through the 18th century, certainly relative to other great powers, and probably in absolute terms too. Meanwhile, how was society in Latin America evolving? My impression is that here too, resentment had been building up for some time against the pretensions and material privileges of "the Peninsulares," actual Spaniards as the system deemed them, those born in Spain themselves, versus people of pure Spanish descent but born in the Americas, versus people of mixed Spanish and Native or African blood. And of course the Indians had expressed their own discontent with being ruled by Spain quite a lot over the centuries--if we imagine them effectively subdued in much of Latin America, there were places where revolt was extensive and recent. If in addition to rising resentments along these lines we have increasing local development that meant alternatives to Spanish trade for wealth or advancement, the question of the basis of Spanish power in Latin America in general and Mexico in particular becomes very pointed indeed. In other words, even if Napoleon had not eclipsed Spanish power in the New World, and even if Spain were not herself slipping in terms of how many armed men she could raise and send to run and subjugate her paper holdings, we still might anticipate conflicts where the anti-Spanish, New-World based factions get stronger even if Spain does not get weaker. And such conflicts themselves would be draining to Spanish power, even the ones they win.
Throw it all together and it looks bloody impossible that Spain could hold on, certainly not after Napoleon upset the applecart. The only way they could would be if there were no native alternative approaches to self-government. OTL we certainly would not be impressed with the strength and stability of Latin American regimes, but even these, weak as they were, were probably stronger by far than the credibility or raw manpower strength of what Spain could by then muster.
So, for it to be plausible Spain still holds Mexico by 1898, we have to do some pretty heavy-duty point of divergence work, it would seem. I've spoken as though I believe the power of Spain had seen its day, and its decline was inevitable. And in fact I suspect this is pretty much the case.
But I note your challenge/question does not reference the Spanish American empire as a whole, just Mexico. You want the King of Spain to keep ruling New Spain, and the rest of it is apparently optional.
I do think we require that Spain as a whole has to be somewhat stronger than OTL on the eve of Napoleon's invasion. Note that while your challenge does not require us to keep the French Revolution and Nappy around, it certainly does require that the United States exist in some recognizable form in the 19th century. So we can't butterfly away the American Revolution anyhow. If we have that, the probability of the French Revolution as we know it goes up, and while an individual like Napoleon might be easy to butterfly, the configuration of forces that enabled the revolutionary First Republic to weather the storm of foreign hostility to it in large part by revealing the potentials of the levee en masse and new military tactics based on that new force seem rather embedded deeply in the situation of the late 18th century to me. In other words, the Revolution had the means to hand to avoid being crushed from the outside, was quite likely then to succumb to dictatorship from within, and that dictator, whomever they might be, would have at hand massive military power unrealized before in the form of a large French population base able to serve in a new and powerful form; it seems inevitable that unless the Revolution misfires or its leadership(s) fumble badly and let it be crushed, post-revolutionary France comes back as a new and mighty force that will to some degree run wild over Europe. Spain is France's neighbor and quite likely to get entangled in these gyrations. To have it be otherwise, we have to unravel things so as to make the American Revolution less likely or anyway quite different in progress and outcomes. You want the USA to exist, therefore I think you are stuck with a Spain menaced by someone like Napoleon Bonaparte. Might as well keep him then to keep the TL from getting too far out in murky speculation.
But we still need Spain to be stronger, and since the decline of Spanish power in the 18th century had much relation to the rise of British power we do have some sticky work to do before 1776. It is beyond me to do it for you, but let's assume it is done somehow.
We need Spain stronger but maybe not so strong it can simply stand up to Napoleon. Let's say Boney gets into Spain and drives out the current dynasty in favor of putting his brother on the throne as OTL. But the old dynasty's king, family and supporters retreat across the seas, to Mexico.
Meanwhile, in New Spain, and perhaps not in the rest of the Empire of the Indies as it was called, the administrative, social and economic history has been somewhat different. Perhaps only in that Viceroyalty, for some peculiar ATL reason, the regime had become more flexible regarding the status of people born in the New World, and perhaps of mixed descent as well, allowing them to compete for high status with little or no discrimination based on their effectiveness and loyalty. Such a policy may account for New Spain being a more lucrative source of revenue and perhaps despite being more heavily taxed to extract it, richer per capita. The upshot might possibly (not certainly, but let us say it is the case here) be more widespread and stronger loyalty to the monarchy, especially among potentially leading classes. For this reason the escaping Spanish monarchy flees to Veracruz and settles to rule its overseas empire and claim to rule Spain from there. There, soldiers and officials from Spain reinforce the Viceroyalty's own forces. As a Coalition ally of Britain the Spanish king in exile develops New Spain as a resource, compounding British RN forces with New Spanish ships, making New Spanish revenues available to hire or recruit new troops--including levies of the Mexican people, some (very few, but some) of whom eventually rise to high rank and influence. As the fortunes of the Napoleonic Wars progress, the Coalition is eventually victorious as per OTL and among other things, the Spanish monarchy returns home to rule Spain again. But it is influenced by its experience in the New World. New Spain has been reorganized to be more productive; New Spanish subjects are added to the pool the king and his government, and private Spanish interests, have to draw on. There may or may not be rebellions there but they are put down.
What happens to the rest of the Empire of the Indies is up to the author; I'd think there surely would be knock-on effects making the claim of the Spanish crown stronger and weakening revolution somewhat, but it may still be that South America goes its own way. I'd predict that New Spain may provide a stronger base for holding some or all of Central America, but maybe not. In any case, per challenge, New Spain, keeping that name (though I and perhaps some ITTL people might sometimes refer to Mexico and Mexicans, probably emphasizing the native people in the latter case--in any case it means part of New Spain) remains under the Spanish Crown.
Having got past the crucial point where we must strive to keep convergent facts such as the presence and nature of the United States of America while accounting for a major divergence, we are now freer to take speculations different ways. What about slavery policy for instance? I believe slavery was always legal in Spanish America (although more paternalistically regulated than in the British colonies and US states). Mexico as a revolutionary republic abolished it, hence the need for the Anglos from the USA settled in Texas to abjure it (as well as convert to Catholicism). Would the Spanish king support slavery as long as they did OTL, as long as it remained legal in Brazil--which is to say, well after the US Civil War OTL? Would they conservatively keep it as a technical legality but bow to liberal trends (as well as certain advice from certain sections of the Catholic Church) and perhaps British influence and restrict it more and more, with slaves given more and more rights and more and more pressure toward emancipation? Or would they abolish it early, perhaps as early as the British Empire did or even before?
It has a lot of bearing on the fate of Florida. We need not strictly assume Florida was restored to Spanish control in the wake of the American Revolution--indeed we need not strictly assume Spain ever lost it in the first place. But the latter seems likely and without it we might butterfly some support for the AR in the south; and given a Patriot victory, the confirmation of the USA, and that the Americans would be strong enough to demand the British vacate control of Florida but not so strong as to seize it for themselves, the British giving it back to Spain in the treaty seems pretty much a foregone conclusion. So now our stronger Spain, with a firm grip on New Spain and therefore an even keener than OTL interest in Cuba as a transit point between the Spains, would have a firmer interest in Florida. With a strong grip on New Spain and hence access to Mexican resources and people, Spain has more power to defend both Cuba and Florida. She can settle Mexicans of various classes there for instance.
The USA OTL had many interests in Florida, most of which carry over here. A glance at the map shows one strong factor--the desire to round out the holdings on the mainland so as to eliminate a possible line of attack by a hostile coalition that might include Spain. Related is a desire to control the Strait of Florida, not only to augment foreign trade in the Caribbean (which in this ATL would mainly be with various ports all within New Spain anyway, notably if NS expands to include Central America--Spain might possibly mandate that US merchants take their goods to Havana, trade them there and leave coastwise carriage to Spanish or perhaps also British shipping) but to communicate with US holdings in "West Florida" that we were conceded OTL and presumably here in the original peace treaty with Britain--land that now forms the coastal parts of Alabama and Mississippi.
But aside from these reasons, a major factor in the drive for the US to acquire Florida was the issue of fugitive slaves. Slaves in Georgia, Alabama and perhaps farther afield, learning that Florida was Spanish territory, fled there and being permitted to remain as refugees, often joined Native tribes, notably the Seminole. Figures like Andrew Jackson therefore led raids into Spanish Florida to capture such slaves, punish their Native protectors, and punish Spain for tolerating it.
So the Spanish monarchy's attitude toward slavery is going to be relevant here. If he is emancipationist on moral grounds (even if some slavery continues to be legal in Spanish holdings somewhere) he will frown on the Americans' zeal. Fugitive slaves also strike me as excellent human resources for building up a loyal local population from which to recruit defensive militias to supplement royal Spanish arms especially in defending Florida itself--their new homeland of freedom. On the other hand if the monarchy is strongly supportive of the slaveholding classes and their "property rights," he might bow to American arguments that he cannot allow slaves to escape to his holdings and should round them up and return them, or conceivably pay compensation--but what the American slaveholders want is for him to close the border. Or to annex Florida themselves for this and other reasons of course!
OTL standard US grade school history books (at least the ones I saw in the 1970s) say that Florida was purchased from Spain for so many millions of dollars. A million dollars certainly went a long way in those days, and even a Spain three or four times richer due to holding New Spain plus probable synergies strengthening their whole Empire as a result might not sneer at a sufficient number of them for giving up Florida. Florida itself was after all an unprofitable backwater that had nothing other parts of the Empire didn't offer, full of swamps and surly Indians not to mention all those fugitive slaves of dubious Christian orthodoxy. But Florida was also a line of defense for Cuba; with Florida and enough good ships Spain controlled the Strait of Florida, not splitting it with the Yankees. Our textbooks mention the multi-million dollar carrot the President offered (I think it was $20 million though I may be much mistaken) but not so much the sharp stick of Jackson's invasions that helped convince Madrid it was an offer they could not refuse.
If the king of Spain is stubborn enough, even if he is on the whole pro-slavery, he might instead choose to reinforce Florida, stationing troops and ships at Saint Augustine, at Appalachicola and Pensacola, and as I suggest settling the fugitive slaves and arming them as self-defending militia, and defying the Americans to try to keep on invading and see what reception they get.
Thus you see long before 1898, Spain holding New Spain, once we've specified how they might do it, can have drastic consequences. The USA might still get Florida, and pay millions for it, but have to spend more millions and a bunch of lives to get military possession of it first. And a Spanish Empire backed by New Spanish wealth, particular if NS is being more dynamically managed, might not be easy to defeat at all. Even if the Americans do manage to grab say the vulnerable panhandle with its minimal development, they might have a hard time taking the southern peninsula with its deep and widespread swamps, stubborn Seminole population, and relatively narrow front for Spaniards (including Mexicans) supported by natives and fugitive slaves concentrated there by Union advance. There might be a compromise and Spain continues to hold some part of the southern peninsula to cover the Strait and Cuba, and the swamps the central peninsula still might be a fugitive refuge. For these reasons the USA might not give up until they get it all, but it would not be cheap if Spain chooses to fight. The Spanish can also deploy a significant navy, one they would be better able to pay for with New Spain and would need all the more with these far-flung yet lucrative possessions so important; indeed New Spain may host major shipyards, and Mexican subjects may supply many of the crews. Now if put to it, the USA of the early 19th century could also fund and construct and man quite a navy too--OTL Navy funding tended to suffer because of legal mandates to intercept illegal attempts to import slaves from overseas, which largely Northern (and to a remarkable degree also African-American) officers and crews stubbornly upheld despite the disinterest in enforcement of these laws by the Southern states--who therefore defunded the Navy. So the confrontation would be large at sea as well, with Spanish forces probably descending in great force on West Florida and of course cutting off US trade out of the Mississippi river region.
I seem to have forgotten the Louisiana Purchase, have I not? Let us say it went forward between American and French negotiators as OTL, and Jefferson took the deal. A stronger Spain, even on the ropes in exile in New Spain (Napoleon being a decade short of being defeated here) might object more strongly to this, as like Florida Louisiana had been deeded over in full to Spain and Napoleon simply stole it from the point of view of an exiled dynasty. I'd think this would strengthen British objections as well. If the Americans nevertheless insist on taking the deal perhaps at the moment there is nothing the Coalition would do about it, having bigger fish to fry regarding France. But come the War of 1812 if we assume that happens on schedule, perhaps the British would make a stronger showing invading Louisiana and New Orleans. Indeed perhaps with this grudge, Spain goes all in with Britain, and the strategic issue of Florida is raised earlier. (Perhaps the USA takes much or all of Florida in this war, as fair spoils if Spain attacks. But surely that would be a major diversion of forces the USA could raise in this controversial war, would it not deplete US capabilities elsewhere?) Maybe instead Spain sits it out, having still not got Spain itself back from Nappy yet. But then too the grudge from the theft of Louisiana as Madrid sees it would carry over to the later decades and have some bearing on the cost to the US of getting Florida--if the US ever gets it at all. This would not be the first TL in which I've been charmed and bemused by the notion of a Spanish Crown owned Florida whose northern panhandle is largely settled by freedman communities serving the Spanish crown as yeoman militiamen defending themselves with Spanish training, command, funding and backing.
Texas--there would be far less reason for the Viceroyalty of New Spain to seek to settle the northeast march of New Spain with of all people, US expatriates. A stronger richer New Spain enriching a larger richer Spanish Empire could probably come up with some loyal Mexicans to settle there, or some Spaniards. If they must settle some English speakers Spain probably has good relations with Britain and can offer land for Catholic British colonists, no need for them to convert if they are Catholic already! The formation of Texas as we know it seems quite unlikely. And there goes our OTL pretext for invading Mexico in the 1840s! Here the pretext might possibly be opposition to monarchy on American soil, or just plain greed, but we'd be attacking from farther north and east, and attacking a nation with deeper pockets and more far-flung resources including a serious navy, and possibly still the Florida front to attack us on.
Would US power still be such that we steamroller New Spanish force and take vast swathes of their northern territories at saber point, again offering a bribe to sweeten the deal a bit? Maybe and maybe not, but even if the Empire of Spain is caught with her pants down, it is not just Mexico we defeat, it is that Empire. Presumably, if the US really is destined to prevail, we would by then have taken Florida and perhaps Cuba into the bargain, though the farther we go the more it would cost, and the more conquered peoples we'd have to swallow.
I'd think that a Spanish Empire that bounced back from Napoleonic humiliation with the help of a loyal New Spain would be economically more dynamic than either Spain or Mexico was OTL. Remember that in addition to its holdings in the Western Hemisphere, Spain has the Philippines as well. With all parts of her remaining empire being more developed, seized Spanish territories would generally be filled with more sullen former Spanish subjects who would be more strongly loyal to the Spanish crown and less liable to accept Yankee rule. True in Florida, true in Cuba and Puerto Rico, and probably true in a California that might enjoy heavier, earlier development from a richer Mexico. Might not be much a change in the vast swathes of desert highlands between Texas and California seized OTL; the Spanish didn't do much with most of that except for New Mexico and even that region might be bypassed by a general rise in Mexican prosperity as part of New Spain. But other than vast empty and harsh lands that took generations for Americans to figure out how to develop and are largely depopulated even today, the lands taken by a rosy scenario US victory in a War with Spain that rectifies the map to OTL as of 1850 would be more of a Latino pill to swallow; I suspect that even if they do reconcile to US citizenship they will affect US culture more strongly. And they just might prove dangerously disloyal in the face of a New Spain that is merely one arm of a Spanish Empire that might be a serious force to reckon with in the later part of the 19th century and into the 20th.
More likely it seems to me that even if the USA does manage to get some gains, the ATL map will show Spain holding on stubbornly to land that will never become part of the USA ITTL. Such as southern Florida, such as a Cuba that the US never will invade successfully, such as Puerto Rico, such as large swathes of the OTL Southwest the US can never claim ITTL. Perhaps the Yanquis get San Francisco, but not Los Angeles with a border on the Tehachapi mountains? Perhaps the Colorado River forms a border, New Mexico remains Nuevo Mexico in Nuevo Espania?
Or it could be that, contemplating the balance of power and the risk that the British might join with Spain for various reasons, the Yankees prudently avoid going to war with Spain at all and Florida, Cuba, and all of the Spanish claims of the southwest remain honored indefinitely as Spain moves into the 20th century a considerably stronger power in Europe and a strong contender for second power in the Western Hemisphere after a USA that might someday acquire Alaska and Hawaii, but will never have California? Which is Spanish!
There is still time in the 20th century for Spain to get messed up pretty royally, but probably never to fall so low as OTL. Certainly various imperialists will hardly see the Philippines as easy pickings, if a prosperous empire finds the wisdom to govern more and more through local notables and invest in both developing and defending the archipelago. Japan might be able to take them anyway, against native will. Who knows which side the Spanish might side with in a version of the Great War, or would they like the USA stay neutral? If Spain goes one way, will the Yankees automatically go the other?
The Civil War (Spanish I mean, American seems pretty darn likely) of OTL is surely butterflied away, but maybe another one, earlier or later, is in the cards. After all we've speculated that New Spain is loyal to a monarchy that might well be more shrewd and statesmanlike than OTL--but it remains an absolute monarchy even so. Will its officials remain astute and clever? If they do does that mean Spain will liberalize and become constitutional? If it does--will Mexicans in New Spain get the same representation Spaniards in Old Spain do? Will the Empire become some kind of Commonwealth with semi-autonomous regions in Europe, America and the Pacific? Or will the latter two find themselves in an invidious patronized position they resent? Might a stubborn absolutist monarch actually play that card to get New Spanish and Filipino support to continue his status and stand against Spanish liberals? Might Spain indeed come to be in effect a European colony of a Mexican-Filipino dictatorship? Or must democracy progress in all three regions? Must that lead to divisive regional nationalism that splits up an Empire that withstood the worst Napoleon or Americans could do to it?
All this is a matter of details emerging from very specifically worked out outcomes of the general proposition that New Spain might somehow, when the chips are down, be an asset rather than a net liability to the Spanish Empire come the early 19th century. As I say I think the key is making an opportunity society in the Viceroyalty linked to the monarchy.
Without working out how that could have been done before the end of the 18th century, I don't see how New Spain can go on existing at all.