• Resolved Damien

    (@takster)


    Hi there.

    I’m not the best with this stuff and find myself stuck and a little unsure with getting data from a loop I require. I have a like/rating plugin that stores the votes & page ID in its own table, called wp_likes_count.

    Here’s a peek at it
    http://i.imgur.com/2NixN.png

    I’m trying to order my posts by most liked with pagination included.
    As I have little experience I’m sure I’m going about this the wrong way.

    I’m not entirely sure but I’m guessing I could work
    SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC into a better $wpdb query somehow? I’m unsure how to put it all together.

    http://codex.wordpress.org/Class_Reference/wpdb

    I’ve tried this…

    <?php
    global $wpdb;
    $total = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC";
    $totalposts = $wpdb->get_results($total, OBJECT);
    $ppp = intval(get_query_var('posts_per_page'));
    $wp_query->found_posts = count($totalposts);
    $wp_query->max_num_pages = ceil($wp_query->found_posts / $ppp);
    $on_page = intval(get_query_var('paged'));
    if($on_page == 0){ $on_page = 1; }
    $offset = ($on_page-1) * $ppp;
    $wp_query->request = "SELECT like_pid FROM " . $wpdb->prefix ."likes_count ORDER BY like_count DESC LIMIT $ppp OFFSET $offset";
    $pageposts = $wpdb->get_results($wp_query->request, OBJECT); ?>
    <?php if ($pageposts): ?>
      <?php foreach ($pageposts as $post): ?>
        <?php setup_postdata($post); ?>
    
    // do stuff
    
     <?php endforeach; ?>
        <?php else : ?>
       <p>No matching entries found.</p>
        <?php endif;?>

    This shows everything but the actual content. Pagination works and I can see my loop template markup repeated in the source of the page like it is counting the articles correctly, yet unable to pull the content to actually fill them. Close but no cigar? Am I even going about this the right way? Driving me nuts 🙂

    Thanks for any help.

  • The topic ‘Best way to query data from database?’ is closed to new replies.