I am using the code below to pull a random post of my site every 6 hour.
if ( false === ( $social_trans_post_id = get_transient( '$social_trans_post_id' ) ) ) {
$args = array('numberposts' => 1, 'orderby' => 'rand');
$social_trans = get_posts($args);
set_transient('$social_trans_post_id', $social_trans[0]->ID, (60*60*6));
} else {
$args = array('post__in' => array($social_trans_post_id));
$social_trans = get_posts($args);
}
To integrate with Twitter, I’d like to only pull posts with 140 characters or less.
I know about <?php echo substr(($post->post_content), 0,140); ?>
which I am using already as a temporary solution.
I tried to setup a condition and this is where I got stuck:
if ( false === ( $social_trans_post_id = get_transient( '$social_trans_post_id' ) ) ) {
$args = array('numberposts' => 1, 'orderby' => 'rand');
$social_trans = get_posts($args);
if (strlen( $social_trans->post_content > 140 ) ) {
// Pull another post?
}
set_transient('$social_trans_post_id', $social_trans[0]->ID, (60*60*6));
} else {
$args = array('post__in' => array($social_trans_post_id));
$social_trans = get_posts($args);
}
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.
After that your code becomes something like:
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.