如果你想发很多帖子(或者只是想减少查询次数),我建议你重新写一点。
首先,构建一个过滤器函数来修改您将要进行的查询。
function filter_query_add_likes( $clauses, WP_Query $wp_query ) {
if ( !is_admin() && !$wp_query->is_main_query() ) {
global $wpdb;
# Add your wanted meta value in as times_liked
$clauses[\'fields\'] .= \', IFNULL( meta_like.meta_value, 0 ) as times_liked \';
# Join the postmeta field based on the post id and the key wanted
# - this assumes you only have one times_liked meta for each post id!
$clauses[\'join\'] .= <<<SQL
LEFT JOIN {$wpdb->prefix}postmeta AS meta_like ON meta_like.post_id = {$wpdb->prefix}posts.ID AND meta_like.meta_key = \'_like_amount\'
SQL;
}
return $clauses;
}
接下来,在运行查询之前使用该过滤器,以便在每篇帖子中返回您的喜欢字段。
function my_plugin_options() {
# Same as what you did, just using heredoc
echo <<<HTML
<p>Table of Likes</p>
</div>
<table>
<tr>
<td>Post</td>
<td>Number of Likes</td>
</tr>
HTML;
$like_args = array(
\'post_type\' => \'post\',
\'order\' => \'DES\',
\'post_status\' => \'publish\'
);
# Set our new filter query to apply for this query
add_filter(\'posts_clauses\', \'filter_query_add_likes\', 10, 2);
$like_loop = new WP_Query( $like_args );
# Remove our filter query to avoid touching other queries on accident
remove_filter(\'posts_clauses\', \'filter_query_add_likes\', 10, 2);
if ( $like_loop->have_posts() ) {
while ( $like_loop->have_posts() ) {
# using next_post like this pulls your posts out for easy access
$current_post = $like_loop->next_post();
# your times_like (from the filter) can now be accessed without
# having to do an extra query with get_post_meta()
$likes = $current_post->times_liked;
# your title can be pulled right in if wanted
$title = $current_post->post_title;
# Draw your column
echo <<<HTML
<tr>
<td>{$title}</td>
<td>{$likes}</td>
</tr>
HTML;
}
}
# End the table
echo "\\r\\n</table>";
}
这可以做几件事:
现在,您只需使用一个查询就可以拉入所有要显示的结果,您可以轻松地从post对象中拉入任何需要的内容,包括喜欢该帖子的次数如果一篇文章还没有赞数,它将收到0,因为编辑fields子句时调用了ISNULL总的来说,比使用get\\u post\\u meta要快得多,尤其是在处理大量帖子的情况下。