WordPress.org

Ready to get started?Download WordPress

Forums

How to select posts from certain category with MySQL? (2 posts)

  1. Swennet
    Member
    Posted 1 year ago #

    Hey everyone. I'm trying to count the amount of posts from a certain category by one author to display on the author.php page. However, I don't know which query to use for that.

    <?php $curauth = $wp_query->get_queried_object();
    $post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'") ?>

    What do I add to only display posts from, say, category ID 3?

  2. vtxyzzy
    Member
    Posted 1 year ago #

    I think this is what you want:

    $curauth = $wp_query->get_queried_object();
    $cat_id = 32;
    $auth_id = $curauth->ID;
    $sql = "SELECT COUNT(*)
    FROM $wpdb->posts p
    JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
    WHERE post_author = $auth_id
    AND post_type = 'post'
    AND post_status = 'publish'
    AND post_date <= NOW()
    AND tr.term_taxonomy_id = $cat_id
    ";
    $post_count = $wpdb->get_var($sql);
    echo "COUNT: $post_count<br />";

Topic Closed

This topic has been closed to new replies.

About this Topic