2
votes

I'm building a voting system in WordPress and I'm having trouble ordering posts by post meta count. I'm setting the meta values as follows:

$post_id = 1;
$user_ip = '0.0.0.0';

add_post_meta( $post_id, 'my_vote', $user_ip );

That works great but I can't figure out how to order posts by the number of votes. I tried running it like this but it just takes a single value of a post meta (the first one) and orders by it's value:

$args = array(
    'posts_per_page'    => -1,
    'orderby'           => 'meta_value_num',
    'order'             => 'DESC',
    'meta_key'          => 'my_vote',
);

$query = new WP_Query( $args );

Is there any way to order by the count of the post meta array? If I run count( get_post_meta( $post_id, 'my_vote' ) ) it'll show a proper count of votes.

1

1 Answers

0
votes

If you want to go by simple method then add another meta for count the votes.

Check:

add_post_meta( $post_id, 'my_vote', $user_ip );
// Add code below this line

$count = get_post_meta( $post_id, 'my_vote_count', true );
$count = empty( $count ) ? 1 : ($count + 1);

update_post_meta( $post_id, 'my_vote_count', $count );

Then change the query:

$args = array(
    'posts_per_page'    => -1,
    'orderby'           => 'meta_value_num',
    'order'             => 'DESC',
    'meta_key'          => 'my_vote_count',
);

$query = new WP_Query( $args );