0

How can I list posts in a descending order of the $json_data->data[0]->total_count values ? I want to display top shared posts descending, but I can't really use WP_Query or query_posts the right way.

require('../wp-blog-header.php');
query_posts('&showposts=-1');

while (have_posts()) : the_post();

    if ( has_post_thumbnail() ) {
    the_post_thumbnail( array(40,40) );
    }

    $url = get_the_permalink();
    $json = file_get_contents( 'https://graph.facebook.com/fql?q=SELECT%20like_count,%20total_count,%20share_count,%20click_count,%20comment_count%20FROM%20link_stat%20WHERE%20url%20=%20%27' . $url . '%27' );
    $json_data = json_decode($json, false);
    echo $json_data->data[0]->total_count;

    endwhile;

The above code shows posts and total share count but not in a descending order because yet I haven't applied any rule.

Any thoughts ?

Thanks in advance!!

1

You can store the counts as key and link a value and sort them before display like this :

$sort_tab = array();
while (have_posts()) : the_post();

if ( has_post_thumbnail() ) {
the_post_thumbnail( array(40,40) );
}

$url = get_the_permalink();
$json = file_get_contents( 'https://graph.facebook.com/fql?q=SELECT%20like_count,%20total_count,%20share_count,%20click_count,%20comment_count%20FROM%20link_stat%20WHERE%20url%20=%20%27' . $url . '%27' );
$json_data = json_decode($json, false);
$sort_tab[$json_data->data[0]->total_count] = $url;

endwhile;
sort($sort_tab);

foreach($sort_tab as $count=>$link)
{
    echo $link.' has '.$count.' votes';
}
7
  • Thanks a lot @Antoine !! works like a charm! Still, it doesn't show the entire posts only 18 out of total..
    – Ismail
    Apr 27 '15 at 13:44
  • 1
    You are welcome. Instead of query_posts, I personnaly prefer to use WP_Query class. In your case that should be : $query = new WP_Query(array('posts_per_page'=>-1)); Also, in your while, replace have_posts and the_post by $query->have_posts and $query->the_post. Don't forget to add wp_reset_query() after endwhile; Tell me if it works better =)
    – Sladix
    Apr 27 '15 at 15:40
  • Thanks a lot again, but unfortunately it still shows data for 18 posts only, I don't know what I am missing. Here's my code: pastebin.com/gUKti9hR
    – Ismail
    Apr 27 '15 at 16:17
  • 1
    This may sound silly but ... are you sure you have more than 18 records in the database ?
    – Sladix
    Apr 28 '15 at 6:59
  • 1
    According to the documentation, $query = new WP_Query( 'posts_per_page=-1' ); should show all your posts. Maybe you can try to log $query->$post_count to see how many posts the query does retrieve
    – Sladix
    Apr 28 '15 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.