How to query WordPress posts bycustom field with a max characters’ length

No, out of the box there isn’t. There are alternatives but the best solutions will require knowledge of your reason for wanting this.

For example, if your goal is to show full quotes on the homepage and avoid a box that’s too large and disrupts the design, you could have:

  • A CSS based solution
  • A custom taxonomy with a “show on homepage” tag ( protip: this would be orders of magnitude faster than your meta query )
  • A tag to indicate if the quote falls into a certain character length range, which can then be picked up in your query

However without that information, the only optimal answer is no, WP_Query can’t do string manipulations, and can only check if it’s equal to or not equal to, or searches, as well as numerical checks on number values.

Perhaps with a raw SQL query it could be done, but that would be an expensive check on an already expensive query. Simpler queries have brought down entire servers under moderate load, and I would expect any page containing your meta query will have major performance problems even without this addition.

My recommendation:

  • Figure out if the quote is too long when it’s saved, and add a tag, not when you’re querying
  • Look for that tag when querying, don’t look at the character count
  • Don’t use random order, instead try a random date
  • If the quote is always different then the page can’t be cached, consider loading multiple quotes in javascript and doing the selection client side instead, or via a call to the REST API