Fetch a post under certain no of words or characters in wordpress? -


is possible fetch post content under 140 characters or 25 words ?

if possible how it

here 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(); } 

character count easy, can add condition and char_length(post_content) < 140 clause.

word count more difficult because there no built in mysql function counting words. can find simple solutions don't work in every use case complete solutions use stored functions. i'll use simple solution sake of example.

what need add filter clause , apply 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 .= ' , (                     char_length(post_content) < 140 or                     (length(post_content) - length(replace(post_content, ' ', ''))+1) < 25                 ) ';      return $where; } 

notice remove filter function called. don't apply same condition every query.

you should aware both of conditions costly compared simple lookup on column value (especially word count). neither can utilize indexes. if have large number of posts may run performance issues if you're running query frequently. better solution might calculate word , character count when post created/updated , store meta data.


Popular posts from this blog