这是您的代码包装在插件中。重要的是prepare()
s输入,因此查询是安全的。您可以定义两个参数:偏移量和;限度这些基本上就是SQLLIMIT
.
如果你对插件没有任何用处,只需停用它,因为它不会做任何事情-它的输出附加到一个过滤器…
$most_commented = apply_filters( \'wpse70027_display_comments\', 0, 3 );
// Now process the result in your template...
…它可以简单地放入任何模板文件中。
<?php
/**
* Plugin Name: (#70027) »kaiser« Get Most Commented.
* Description: Just place the filter in your themes template file and you\'re ready to go.
*/
function wpse70027_get_comments( $offset = 0, $limit = 10 )
{
global $wpdb;
static $instance;
// Validate input
$offset = absint( $offset );
$limit = absint( $limit );
// Prevent wrong user input
0 > $offset AND $instance[\'offset\'] = 0;
// Setup offset/limit as 0/10 on the 1st run
! isset( $instance[\'offset\'] ) AND $instance[\'offset\'] = $offset;
! isset( $instance[\'limit\'] ) AND $instance[\'limit\'] = $limit;
// Setup the query string
! isset( $instance[\'query\'] ) AND $instance[\'query\'] =
"
SELECT $wpdb->posts.ID, $wpdb->posts.post_title,
COUNT($wpdb->comments.comment_post_ID) AS cmt
FROM $wpdb->posts, $wpdb->comments
WHERE comment_approved = \'1\'
AND $wpdb->posts.ID = $wpdb->comments.comment_post_ID
AND post_status = \'publish\'
AND comment_status = \'open\'
GROUP BY $wpdb->comments.comment_post_ID
ORDER BY cmt
DESC
LIMIT %d, %d
";
! isset( $instance[\'posts\'] ) AND $instance[\'posts\'] = array();
// Three conditions trigger a new query:
# A) Plugin is running the first time and \'posts\' isn\'t set
# B) The input offset is below the default offset
# C) The input limit is above the default limit
if (
! isset( $instance[\'posts\'] )
OR ! in_array( $offset, range( $instance[\'offset\'], $instance[\'limit\'] ) )
OR ! in_array( $limit, range( $instance[\'offset\'], $instance[\'limit\'] ) )
)
{
// Adjust the range
$instance[\'offset\'] = $instance[\'offset\'] > $offset ? $offset : $instance[\'offset\'];
$instance[\'limit\'] = $instance[\'limit\'] < $limit ? $limit : $instance[\'limit\'];
$instance[\'posts\'] = $wpdb->get_results( $wpdb->prepare(
$instance[\'query\']
,$instance[\'offset\']
,$instance[\'limit\']
) );
}
// Only return what was requested
return array_intersect_key(
$instance[\'posts\']
,range( $offset, $limit )
);
}
add_filter( \'wpse70027_display_comments\', \'wpse70027_get_comments\', 10, 2 );
不,还有
no difference 当你把它应用到你的功能中时。php文件。唯一的问题是,这段代码将在主题更新或更改时消失,所以最好将其保留在插件中