WordPress: Kategorien ermitteln mit den meisten Artikeln innerhalb x Tage


Um eine solche Abfrage zu realisieren, braucht es ein wenig MySQL in Verbindung mit WordPress. Mit der Funktion getCategoriesWithMostArticlesInLastDays() kann man die beliebtesten X Kategorien innerhalb der letzten Y Tage bestimmen:

function getCategoriesWithMostArticlesInLastDays($categoriesCount, $lastDaysCount)
{
    global $wpdb;
    $querystr = "
    SELECT $wpdb->terms.name AS categoryName,COUNT($wpdb->terms.term_id) AS countCategory, $wpdb->terms.term_id as categoryId
    FROM $wpdb->posts
        LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
        LEFT JOIN $wpdb->terms ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id)
    WHERE
        $wpdb->posts.post_status = 'publish'
        AND $wpdb->posts.post_type = 'post'
        AND $wpdb->posts.post_date > TIMESTAMP(DATE_SUB(NOW(), INTERVAL $lastDaysCount DAY ))
        AND $wpdb->term_taxonomy.taxonomy = 'category'
    GROUP BY $wpdb->terms.term_id
    ORDER BY COUNT($wpdb->terms.term_id) DESC
    LIMIT $categoriesCount
";
    $categoriesWithMostArticlesInLastDays = $wpdb->get_results($querystr, ARRAY_A);
    foreach($categoriesWithMostArticlesInLastDays as  $key => $category)
    {
        $categoriesWithMostArticlesInLastDays[$key]["link"] = get_category_link($category['categoryId']);
    }
    return $categoriesWithMostArticlesInLastDays;
}