我有几个函数正在创建一个管理表,以显示在我的自定义仪表板页面上。我在确定要显示哪些页面的函数方面遇到了一些问题,因为我不知道如何限制我的查询,使其不计算post状态为“自动草稿”或“垃圾”的项目。
有人知道怎么做吗?我需要$totalitems来只计算那些没有这些post状态的项目。以下是我的功能:
/**
* Prepare the table with different parameters, pagination, columns and table elements
*/
function prepare_items() {
global $wpdb, $_wp_column_headers;
$screen = get_current_screen();
/* -- Preparing your query -- */
$query = "SELECT * FROM $wpdb->posts";
/* -- Ordering parameters -- */
//Parameters that are going to be used to order the result
$orderby = !empty($_GET["orderby"]) ? mysql_real_escape_string($_GET["orderby"]) : \'ASC\';
$order = !empty($_GET["order"]) ? mysql_real_escape_string($_GET["order"]) : \'\';
if(!empty($orderby) & !empty($order)){ $query.=\' ORDER BY \'.$orderby.\' \'.$order; }
/* -- Pagination parameters -- */
//Number of elements in your table?
$totalitems = $wpdb->query($query); //return the total number of affected rows
//How many to display per page?
$perpage = 15;
//Which page is this?
$paged = !empty($_GET["paged"]) ? mysql_real_escape_string($_GET["paged"]) : \'\';
//Page Number
if(empty($paged) || !is_numeric($paged) || $paged<=0 ){ $paged=1; }
//How many pages do we have in total?
$totalpages = ceil($totalitems/$perpage);
//adjust the query to take pagination into account
if(!empty($paged) && !empty($perpage)){
$offset=($paged-1)*$perpage;
$query.=\' LIMIT \'.(int)$offset.\',\'.(int)$perpage;
}
/* -- Register the pagination -- */
$this->set_pagination_args( array(
"total_items" => $totalitems,
"total_pages" => $totalpages,
"per_page" => $perpage,
) );
//The pagination links are automatically built according to those parameters
/* — Register the Columns — */
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
/* -- Fetch the items -- */
$this->items = $wpdb->get_results($query);
}
最合适的回答,由SO网友:s_ha_dum 整理而成
WHERE post_status NOT IN (\'auto-draft\',\'trash\')
看起来可以将其添加到基本查询中。
/* -- Preparing your query -- */
$query = "SELECT * FROM $wpdb->posts WHERE post_status NOT IN (\'auto-draft\',\'trash\') ";
这仅仅是一个WordPress问题。为什么不使用
core functions 为了这个?
而且NOT IN
不是一个非常有效的查询。这可能比您预期的要慢。