You should use WP_Query
instead of query_posts()
to avoid overwriting global variables and messing up conditional tags.
https://developer.wordpress.org/reference/classes/wp_query/
To only get posts that are under 180 characters, you’d need to modify the SQL query directly using a filter. This completely untested code should give you something to go on:
add_filter( 'posts_where', 'jabbamonkey_only_fetch_short_posts', 10, 2 );
$your_query = new WP_Query( $args );
remove_filter( 'posts_where', 'jabbamonkey_only_fetch_short_posts', 10 );
function jabbamonkey_only_fetch_short_posts( $where, $query ) {
$where .= ' AND CHAR_LENGTH(post_content) <= 180';
return $where;
}
I threw the code into my homepage, and it spits out the homepage content (not a random post)
<?php
$args = array('numberposts' => 1, 'orderby' => 'rand');
add_filter( 'posts_where', 'only_fetch_short_posts', 10, 2 );
$your_query = new WP_Query( $args );
remove_filter( 'posts_where', 'only_fetch_short_posts', 10 );
function only_fetch_short_posts( $where, $query ) {
$where .= ' AND CHAR_LENGTH(post_content) <= 180';
return $where;
}
while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
Try this version. Be sure the posts table prefix in the CHAR_LENGTH() function is correct for your site.
<?php
$args = array('posts_per_page' => 1, 'orderby' => 'rand');
add_filter( 'posts_where', 'only_fetch_short_posts', 10, 2 );
$your_query = new WP_Query( $args );
remove_filter( 'posts_where', 'only_fetch_short_posts', 10 );
function only_fetch_short_posts( $where, $query ) {
$where .= ' AND CHAR_LENGTH(wp_posts.post_content) <= 180';
return $where;
}
while ( $your_query->have_posts()) : $your_query->the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
The loop you were running was for the main query, not your custom query.
It’s coming together… but right now it’s showing 10 random posts…
If this part correct?
‘numberposts’ => 1
AFAIK numberposts is deprecated but should have still worked. It has apparently been fully removed now, because it doesn’t work for me either. It was replaced with “posts_per_page”. Use that instead (like in my example :P) and you’ll only get one random post returned meeting the WHERE criteria.
Got it. It’s all working now. Thanks for all the help everyone! Final code is below…
<?php
$args = array('posts_per_page' => 1, 'orderby' => 'rand');
add_filter( 'posts_where', 'only_fetch_short_posts', 10, 2 );
$feature_query = new WP_Query( $args );
remove_filter( 'posts_where', 'only_fetch_short_posts', 10 );
function only_fetch_short_posts( $where, $query ) {
$where .= ' AND CHAR_LENGTH(post_content) <= 120';
return $where;
}
while ( $feature_query->have_posts()) : $feature_query->the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>