我有一个插件,它显示了投票计数列表中投票最多的帖子。
The code is placed here: https://gist.github.com/hchouhan/6727356
function dot_most_recommended_posts($numberOf, $before, $after, $show_count, $post_type="showcase" ) {
global $wpdb;
$request = "SELECT * FROM $wpdb->posts, $wpdb->postmeta";
$request .= " WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id";
$request .= " AND post_status=\'publish\' AND post_type=\'$post_type\' AND meta_key=\'_recommended\'";
$request .= " ORDER BY $wpdb->postmeta.meta_value+0 DESC LIMIT $numberOf";
$posts = $wpdb->get_results($request);
foreach ($posts as $item) {
$post_title = stripslashes($item->post_title);
$permalink = get_permalink($item->ID);
$post_count = $item->meta_value;
echo $before.\'<a href="\' . $permalink . \'" title="\' . $post_title.\'" rel="nofollow">\' . $post_title . \'</a>\';
echo $show_count == \'1\' ? \' (\'.$post_count.\')\' : \'\';
echo $after;
}
}
$options = get_option("dot_most_recommended_posts");
if (!is_array( $options ))
{
$options = array(
\'title\' => \'Most recommended posts\',
\'number\' => \'10\',
\'show_count\' => \'1\',
);
}
$title = $options[\'title\'];
$numberOf = $options[\'number\'];
$show_count = $options[\'show_count\'];
echo \'<ul class="mostrecommendedposts">\';
dot_most_recommended_posts($numberOf, \'<li>\', \'</li>\', $show_count);
echo \'</ul>\';
上面的代码是从这个插件中抽象出来的
http://wordpress.org/plugins/i-recommend-this/.
现在,使用上述代码显示的数据是准确的。根据收到的票数显示一个列表。我想知道避免使用原始查询而改用WP\\u查询的最佳方法。
我尝试了下面的代码,但它似乎只显示一些计票数为9的帖子。Updated code with WP_Query - https://gist.github.com/hchouhan/6727363
<?php
$query_top_10_showcase = new WP_Query(
array(
\'post_type\' => array( \'showcase\' ),
\'orderby\' => \'meta_value\',
\'meta_key\' => \'_recommended\',
\'paged\' => $paged
)
);
// Run the loop as normal
if ( $query_top_10_showcase->have_posts() ) :
while ( $query_top_10_showcase->have_posts() ) : $query_top_10_showcase->the_post();
$url = get_post_meta( $post->ID, \'_dot_showcase_url\', true );
$recommended = get_post_meta( $post->ID, \'_recommended\', true );
?>
<p>
<?php the_title() ?> - <?php echo $recommended; ?>
</p>
<?php
endwhile;
else:
// no posts found
endif;
wp_reset_postdata();
?>