Is the keyword customers though? In other words you’ve got to spend money to use the toilet?
In America I can walk in to a restaurant, even a nicer one and ask to use the bathroom and very likely would be shown strait to it. It’s not 100% of the time everywhere, especially places like Times Square, but I’d say that the norm is no spend required.
Obviously can't speak for the entire country of Spain, but that tends to be true here too. The more touristic places, especially closer to the beaches, tend to have "Toilets for customers only" signs though, which is kind of understandable as people start using them as changing rooms otherwise, and get overrun with tourists not really caring about how they leave things.
This is my impression also, there is usually explicit "only customers" where there are genuine problems (overtouristic etc) or where the boss is just weird (even though you may be still told off even without a only-customers sign in some cases). I would say most of the time, under normal circumstances, there is no issue.
Even then, I cannot imagine somebody saying no when telling them "I have a health issue and need to use a toilet", in most cases.
They’re not uncommon but in my experience you tend to find them more in tourist areas with high foot traffic or if there are a lot of homeless people or something along those lines.
And even where the signs and procedures exist, often the rules are not enforced... at least, not against people who appear to plausibly be customers.
If you're a well groomed adult and walk up to the counter at a coffee shop and ask for the code, they'll usually just give it to you no questions asked.
The selective enforcement is the point, because they use these policies to keep away the "types" of people they don't want in the businesses (i.e. unhoused people, teens, etc).