• Resolved Khalid

    (@k-max)


    well, let me share a code i just made to resort posts.
    i made a competition on my site, the user should make a post, the winner is one who gets most Facebook likes.

    i had to fetch posts likes, assign the number to a custom field, then query posts sorted by the custom field value.

    i start by adding a loop before the main loop, and fetch the likes count from facebook:

    query_posts();
    if (have_posts()) : while (have_posts()) : the_post();
    // get facebook likes
    $facebook_api_results = file_get_contents("http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls=" . urlencode(get_permalink()));
    $parsed_facebook_api_results = json_decode($facebook_api_results, true);

    then i create new field and add the facebook likes count number:

    $likes=$parsed_facebook_api_results[0]['total_count'];
    $id=get_the_ID();
    add_post_meta( $id, '_likes', $likes, true ) || update_post_meta( $id, '_likes', $likes );

    then just end the loop:

    endwhile;
    endif;
    wp_reset_query();

    now modify the query posts loop to sort them according to the custom field:

    query_posts('meta_key=_likes&orderby=meta_value_num&posts_per_page=3&cat=' . $mycat);
    if (have_posts()) : while (have_posts()) : the_post();

    am not a coder, i just like to code 🙂

  • The topic ‘arrange posts by facebook likes, template design tutorial’ is closed to new replies.