• I have a static front page that contains links to several blogs. To the right of the blog title on this front page I want to display the total number of posts and comments for each blog. What is the best way to get these totals?

    Below is what I am thinking of at the moment, but may not be effiecient. Is there a better way? Other ideas?


    <?php
    @ $db = mysql_connect('localhost','username','password');
    if (!$db)
    {
    exit;
    }
    mysql_select_db('wp21');

    $qryblog21_posts = "select count(*) -1 as ct from wp01_posts";
    $qryblog21_comments = "select count(*) -1 as ct from wp01_comments";

    $result21_posts = mysql_query($qryblog21_posts);
    $result21_comments = mysql_query($qryblog21_comments);

    $array21_posts = mysql_fetch_array($result21_posts);
    $array21_comments = mysql_fetch_array($result21_comments);

    mysql_close;

    if ($array21_posts && $array21_comments)
    {
    echo $array21_posts[0];
    echo "</br>";
    echo $array21_comments[0];
    }
    ?>

    Any suggestions welcome.

    Thanks in advance.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter deko

    (@deko)

    Thanks for the reply, but that code does not work. Here is the error I get:


    Fatal error: Call to a member function on a non-object in /home/post/public_html/index.php on line 75

    Is the problem due to the fact that the code is on the “front page” and not the blog page?

    Can you please explain why this code is failing and how to fix?

    What is $wpdb->get_var ??

    Thanks.


    $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish'");
    if (0 < $numposts) $numposts = number_format($numposts);
    $numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
    if (0 < $numcomms) $numcomms = number_format($numcomms);
    echo $numposts;
    echo "</br>";
    echo $numcomms;

    Work on my blog in the front page ??
    I missed your reply here. Please post on my blog for faster response.

    > $wpdb->get_var
    get’s a single variable.

    I just tested the code again, works. Can you send me your exact code, unless you solved it yourself?

    I hope you can help me as I am getting the same error in a php file I am working on. In my case, I think it has to do with creating a script file which I want to redirect a Page to. I’ve included the wp-blog-header at the top of my script and included a global $wpdb. What else do I need to include?

    I do ultimately want to make this into a plugin.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to get counts of posts and comments?’ is closed to new replies.