• Resolved barrybell

    (@barrybell)


    Hi – I just need some quick support with writing a custom query… and MYSQL ain’t one of my strong points.

    What I’m after is a query that lists all authors (from my multi-author blog) who have at least ONE published post in a particular category.

    Can anyone help?

    Thanks in advance.

    B

Viewing 4 replies - 1 through 4 (of 4 total)
  • A query by itself will list nothing. I’ll assume you knew that… Anyway, this will provide you an array with the user ‘ID’ and ‘user_nicename’ to those authors:

    $cat_id = 10;
    $authors_in_cat = $wpdb->get_results("SELECT DISTINCT $wpdb->users.ID, user_nicename from $wpdb->users
    	INNER JOIN $wpdb->posts ON $wpdb->posts.post_author = $wpdb->users.ID
    	INNER JOIN $wpdb->term_relationships ON $wpdb->posts.ID = $wpdb->term_relationships.object_id
    	INNER JOIN $wpdb->term_taxonomy ON $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id
    	WHERE $wpdb->term_taxonomy.term_id = '$cat_id'
    	ORDER BY display_name");

    Just assign $cat_id with the category ID number.

    Well Kaf beat me to this, but here’s another version. Wonder which is faster…?

    <?php
    /*
    Get all post author IDs for post belonging to category 3
    */
    $category = 3;
    $query = "SELECT DISTINCT post_author FROM $wpdb->posts ";
    $query .= ", $wpdb->term_relationships, $wpdb->term_taxonomy ";
    $query .= " WHERE 1=1 ";
    $query .= "AND post_type = 'post' ";
    $query .= "AND post_status = 'publish' ";
    $query .= "AND ($wpdb->posts.ID = $wpdb->term_relationships.object_id AND $wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id AND $wpdb->term_taxonomy.term_id = " . $category. " AND $wpdb->term_taxonomy.taxonomy = 'category') ";
    ?>
    
    <?php
    /*
    This section needs Kaf's Plugin http://guff.szub.net/get-author-profile activated to display the results
    */
    $authors = $wpdb->get_results($query, OBJECT);
    if ($authors):
    foreach ($authors as $author):
    get_author_profile($author->post_author);
    ?>
    <li><?php author_profile('firstname'); ?> <?php author_profile('lastname'); ?></li>
    <?php endforeach; ?>
    <?php else : ?>
    <h2> Not Found</h2>
    <?php endif; ?>
    Thread Starter barrybell

    (@barrybell)

    Cheers Kaf – I managed to pull something together myself but ran into probs pulling out anything other than the user_id’s.

    What I’m struggling most with is the new terms/term_taxonomy structure in 2.3 – it’s taking me a long time to get my head around it.

    Thanks again.

    B

    Thread Starter barrybell

    (@barrybell)

    And Michael – thanks too.

    B

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Need help with a custom query…’ is closed to new replies.