If you will be pulling a lot of posts (or simply want to reduce the number of queries made), I’d recommend re-writing things a little bit.
First, build a filter function to modify the query you are about to make.
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;
}
Next, use that filter right before you run your query to get your likes field back in each post.
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>";
}
This does a couple of things:
- You now only use a single query to pull in all results that you want to show
- You can easily pull whatever you want from the post object, including the number of times the post was liked.
- If there is no likes count yet on a post, it will receive 0 due to the ISNULL call made when editing the fields clause.
Overall, much faster than using get_post_meta, especially if you are dealing with a lot of posts.