0

Is it possible to fetch a post with content under 140 characters or 25 words ?

if possible how to do it

here is my random post code

// Random post link 
function randomPostlink(){
$RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand'));
while ( $RandPostQuery->have_posts() ) : $RandPostQuery->the_post();
echo the_permalink();
endwhile;
wp_reset_postdata();
}
Venki
  • 11
  • 5

1 Answers1

0

Character count is easy, you can just add the condition AND CHAR_LENGTH(post_content) < 140 to your where clause.

Word count is more difficult because there is no built in MySQL function for counting words. You can find simple solutions that don't work in every use case as well as complete solutions that use stored functions. I'll use a simple solution for the sake of example.

What you need to do is add a filter to the where clause and apply your additional conditions there:

add_filter( 'posts_where', 'venki_post_length_limit' );

function venki_post_length_limit($where = '') {
    remove_filter( 'posts_where', 'venki_post_length_limit' );

    $where .= ' AND (
                    CHAR_LENGTH(post_content) < 140 OR
                    (LENGTH(post_content) - LENGTH(REPLACE(post_content, ' ', ''))+1) < 25
                ) ';

    return $where;
}

Notice that I remove the filter as soon as the function is called. This is so you don't apply this same condition to every query.

You should also be aware that both of those conditions are costly compared to a simple lookup on a column value (especially the word count). Neither can utilize indexes. If you have a large number of posts you may run into performance issues if you're running this query frequently. A better solution might be to calculate the word and character count when the post is created/updated and store that as meta data.

Community
  • 1
  • 1
Mathew Tinsley
  • 6,805
  • 2
  • 27
  • 37