I want to suggest you another approach.
You can set a meta when you saving a post if its content is less than 140 chars, so then you can simply runs a simple meta query.
add_action( 'save_post_post', function( $id, $post ) {
if ( $post->post_status !== 'publish' ) {
return;
}
if ( strlen( $post->post_content ) <= 140 ) {
update_post_meta( $id, '_under_140', 1 );
}
}, 10, 2 );
After that your code becomes something like:
function get_social_trans_post() {
$social_trans_post = get_transient( 'social_trans_post' );
if ( empty( $social_trans_post ) ) {
$args = array( 'posts_per_page' => 1, 'meta_key'=>'_under_140', 'orderby'=>'rand' );
$social_trans_posts = get_posts( $args );
if ( ! empty( $social_trans_posts ) ) {
$social_trans_post = $social_trans_posts[0];
set_transient( 'social_trans_post', $social_trans_post, 6 * HOUR_IN_SECONDS );
}
}
return $social_trans_post;
}
And where you need the post just call get_social_trans_post()
.
Worth noting that I saved in transient the whole post, not only the id, in this way there is no need to query for post, after get the id. All the serialization / unserialization work is done by WordPress, and what you get is exactly what you stored.
Off course this code will work for posts that you add or update after adding it, but you can run a run-once script to set the meta on your recents posts having the wantend content length.