orderby=meta_value_num creates duplicate posts

I have my facebook likes stored in a custom field named fb_likes. my wordpress post order is sorted by this field, like this.

 'meta_key' => 'fb_likes',
 'orderby' => 'meta_value_num',
 'order' => 'DESC',
 'ignore_sticky_posts' => 1,
 'posts_per_page' => $wp_query->get('posts_per_page'),
 'paged' => $paged

This seems to work fine at first glance, but if you click through the pages, you notice, that some posts are displayed two (or even three) times, even though they’re in the database only one time. Also the post order is messed up and seems to change on its own.

Read More

When I use meta_value instead of meta_value_num it works fine, but then there’s the problem that it sorts like this -> 9,5,4,39,38,37,26 – you get the idea. So I need meta_value_num to work as intended.

what could be the problem?

EDIT:
I use the following code to write the facebook likes to the meta_value of fb_likes. If I could just somehow write to the meta value like this “001” instead of this “1”. Then I could easily use orderby=meta_value and wouldn’t even need meta_value_num.

Is there a way to write to the database like this? 1 like -> 001, 21 likes -> 021

{
        if($post->post_type == 'draft') continue;
        $fb = json_decode(file_get_contents('http://graph.facebook.com/?id='.get_permalink($post->ID)));
        if( !isset( $fb->likes) && isset($fb->shares) )
        {
            $fb->likes = $fb->shares;
        }
        //$fb->likes = isset($fb->likes) ? $fb->likes : 0;
        $this->log("post_id: ({$post->ID}) npermalink: ".get_permalink($post->ID) . "nfb_likes:". $fb->likes . "n"); 
        update_post_meta($post->ID, 'fb_likes', (int)$fb->likes);
    }

Related posts

2 comments

  1. As for the edit (leading zeroes):

    /* will print "001" */
    echo sprintf( "%03d", 1 );
    
    /* will print "00097" */
    echo sprintf( "%05d", 97 );
    

    As for the inital problem:

    Obviously, I believe your problem description, but if 'orderby' => 'meta_value' does not produce duplicate results, neither should a change to 'orderby' => 'meta_value_num'.
    If that’s the only alteration you make, it should only change order…

  2. I fixed it now – I just wrote to the meta_value field with leading zeros already attached and used the normal orderby=meta_value command. So now I have the likes already with leading zeros in my database.

    $myfblikes = sprintf("%04s", (int)$fb->likes);
            update_post_meta($post->ID, 'fb_likes', $myfblikes);
    

    Thanks for the help. I totally understand the point that it should also work with meta_value_num, because this command should really only change the post order. But somehow it doesn’t – so there must be an issue with my meta_value_num. I don’t even know how to put out raw sql because this is the first time I worked with php/mysql 😉

    Anyways, I’m glad I got it working.

Comments are closed.