您发布的函数使用了一个讨厌的自定义SQL查询,这实际上是不必要的,添加一个类别过滤器会使情况更糟,您可以使用WP_Query
对象或get_posts
除了排除受密码保护的帖子,这可以通过连接到posts_where
过滤,这样你就可以:
//function to exclude password protected posts
function exclude_pw_where($where) {
$where .= " AND post_password = \'\' ";
return $where;
}
// function to get latest posts of category
function latest_posts_of_category($no_posts = 5, $before = \'<li>\', $after = \'</li>\', $hide_pass_post = true, $skip_posts = 0, $show_excerpts = false, $include_pages = false, $cat_id = null){
global $post;
$temp = $post;
$args = array(
\'posts_per_page\' => $no_posts,
\'post_type\' => \'post\',
\'post_status\' => \'published\',
\'order\' => \'DESC\',
\'orderby\' => \'date\',
\'offset\' => $skip_posts,
);
if ( $cat_id != null )
$args[\'cat\'] = $cat_id;
if ( $include_pages )
$args[\'post_type\'] = array(\'post\',\'page\');
//add filter to exclude password protected posts
if ( $hide_pass_post )
add_filter(\'posts_where\', \'exclude_pw_where\');
$posts = get_posts($args);
if ( $posts ) {
foreach ( $posts as $post ) {
$post_title = $post->post_title;
$permalink = get_permalink( $post->ID );
$date=date(\'F j, Y\', strtotime($post->post_date));
$output .= $before . \'<span class="date">\'.$date.\'</span><a href="\' . esc_url( $permalink ) . \'" rel="bookmark" title="Permanent Link: \' . esc_attr( $post_title ) . \'">\' . esc_html( $post_title ) ;
if ( $show_excerpts ) {
$post_excerpt = esc_html( $post->post_excerpt );
$output.= \'<br />\' . $post_excerpt;
}
$output .= $after;
}
} else {
$output .= $before . "None found" . $after;
}
echo $output;
//remove the filter if was called
if ( $hide_pass_post )
remove_filter(\'posts_where\', \'exclude_pw_where\');
}
它也可以做同样的事情,但要安全得多,您可以设置最后一个参数$cat\\u id,以通过类别id指定类别(或使用数组的类别列表)。