admin管理员组

文章数量:1122793

I would like to display some stats on my website. For multiple post types I would like something like this: XXX Reviews (XX)

  1. where the first XXX is the total amount which I can get by using wp_count_posts('reviews')
  2. where Reviews is the name of the posttype
  3. where (XX) show how many reviews were added last month or week (still need to decide on that but idea is the same)

I'm only missing point 3, how do I do this most efficient, I know I can use get_posts() and use dynamic vars to pull the data but I think is pretty resourceful right?

I need to do this for 4 post types on my home page, in the future, more might be added.

I would like to display some stats on my website. For multiple post types I would like something like this: XXX Reviews (XX)

  1. where the first XXX is the total amount which I can get by using wp_count_posts('reviews')
  2. where Reviews is the name of the posttype
  3. where (XX) show how many reviews were added last month or week (still need to decide on that but idea is the same)

I'm only missing point 3, how do I do this most efficient, I know I can use get_posts() and use dynamic vars to pull the data but I think is pretty resourceful right?

I need to do this for 4 post types on my home page, in the future, more might be added.

Share Improve this question asked Jun 22, 2015 at 16:53 Boris KampBoris Kamp 1113 bronze badges 3
  • What about running a wp_query for reviews and limit the query for the date time required? – Stephen Rodriguez Commented Jun 22, 2015 at 16:55
  • Isn't a wp_query pretty heavy to run as well? I think get_posts would even be faster. – Boris Kamp Commented Jun 22, 2015 at 20:40
  • get_posts is your answer. Add 'fields' => 'ids' to the get_posts arguments, this way you get only the post ID's. This way you cut up to 99.9% on db queries and time :-) – Pieter Goosen Commented Jul 10, 2015 at 8:28
Add a comment  | 

1 Answer 1

Reset to default 0

Besides this suggestion, here is a simple SQL query adapted from the core wp_get_archives function:

SELECT 
    YEAR(post_date) AS `year`, 
    MONTH(post_date) AS `month`, 
    count(ID) as posts 
FROM 
    wp_posts 
WHERE 
    post_type = 'post' AND post_status = 'publish' 
GROUP BY 
    YEAR(post_date), MONTH(post_date) 
ORDER BY 
    post_date DESC

This would provide with a structure like this:

+------+-------+-------+
| year | month | posts |
+------+-------+-------+
| 2015 |     5 |     1 |
| 2015 |     4 |     1 |
+------+-------+-------+

You can use $wpdb->get_results for this query.

本文标签: phpCount posts per posttype for last monthweek