如题,我们在使用wordpress进行相关定制开发时,可能会遇到程序内置的查询无法满足我们实际数据查询需求,所以就需要我们通过定制mysql语句来进行相关的查询。

wordpress使用sql查询的方法:
1、先定义全局类:
global $wpdb;
2、通过$wpdb类来查询相关的数据;
$wpdb提供了多种查询方法: 如:get_results 直接返回查询结果,get_rows返回多行,get_var返回单个值等。
我们这里不过多的描述基础,直接上代码:
下面是一段查询一段时间内热门文章的代码,是根据文章评论数量来判断是否热门:
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  | 
						function most_comm_posts($days=30, $nums=5) {     global $wpdb;     date_default_timezone_set("PRC");     $today = date("Y-m-d H:i:s");     $daysago = date( "Y-m-d H:i:s", strtotime($today) - ($days * 24 * 60 * 60 * 10) );     $result = $wpdb->get_results("SELECT comment_count, ID, post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' and post_type='post' and post_status='publish' ORDER BY comment_count DESC LIMIT 0 , $nums");     $output = '';     if(empty($result)) {         $output = '<li>暂时没有数据</li>';     } else {         foreach ($result as $topten) {             $postid = $topten->ID;             $title = $topten->post_title;             $commentcount = $topten->comment_count;             if ($commentcount >= 0) {                 $output .= '<a class="list-group-item visible-lg" title="'. $title .'" href="'.get_permalink($postid).'" rel="bookmark"><i class="fa  fa-book"></i> ';                     $output .= strip_tags($title);                 $output .= '</a>';                 $output .= '<a class="list-group-item visible-md" title="'. $title .'" href="'.get_permalink($postid).'" rel="bookmark"><i class="fa  fa-book"></i> ';                     $output .= strip_tags($title);                 $output .= '</a>';             }         }     }     echo $output; }  | 
					
以上代码是获取到了一段时间内所有分类的热门文章,我们现在的需求是热门文章排除分类ID 为29的文章;通过系统查询很容易实现,不过在sql语句内如何实现呢,直接上代码:
| 
					 1  | 
						$result = $wpdb->get_results("SELECT comment_count, ID, post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' and post_type='post' and post_status='publish' and ($wpdb->posts.ID NOT IN (SELECT object_id FROM $wpdb->term_relationships	WHERE term_taxonomy_id IN (29) ) ) ORDER BY comment_count DESC LIMIT 0 , $nums");  | 
					
原理,我们这里使用了关联查询,wp_term_relationship表记录了文章ID和分类ID对应关系,所以,我们在where语句后面跟上了 not in 方法,来排除分类为29的文章。
大神勿喷,给度娘交的作业。如果碰巧帮助到你,帮给写一条评论也是不错的。

谢谢分享,很有用!