在wordpress中获取特定字数或字符数下的帖子?
是否可以获取内容少于140个字符或25个单词的帖子 如果可能的话,怎么做 这是我的随机邮政编码在wordpress中获取特定字数或字符数下的帖子?,wordpress,Wordpress,是否可以获取内容少于140个字符或25个单词的帖子 如果可能的话,怎么做 这是我的随机邮政编码 // Random post link function randomPostlink(){ $RandPostQuery = new WP_Query(array('post_type'=>array('tip'),'posts_per_page' => 1,'orderby'=>'rand')); while ( $RandPostQuery->have_posts()
// 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();
}
字符计数很简单,只需将条件
和字符长度(post\u content)<140
添加到where子句中即可
单词计数更困难,因为没有内置的MySQL函数来计算单词。您可以发现,这并不适用于所有用例以及使用的完整解决方案。为了举例,我将使用一个简单的解决方案
您需要做的是在where子句中添加一个筛选器,并在其中应用附加条件:
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;
}
add_filter('posts_where','venki_post_length_limit');
函数venki_post_length_limit($where=''){
移除过滤器('posts_where'、'venki_post_length_limit');
$where.='和(
字符长度(后内容)<140或
(长度(post_内容)-长度(替换(post_内容,,'')+1)<25
) ';
返回$where;
}
请注意,我会在调用函数后立即移除过滤器。这样,您就不会对每个查询应用相同的条件
您还应该知道,与对列值(尤其是字数)进行简单查找相比,这两种情况的成本都很高。两者都不能利用索引。如果您有大量文章,如果您经常运行此查询,可能会遇到性能问题。更好的解决方案可能是在创建/更新帖子时计算字数和字符数,并将其存储为元数据