RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.59%*) • Fixed: 5.39% (6.59%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.48%*) • Investment PI: 5.39% (6.59%*)

Display the Total Number of Scheduled, Draft, or Published Posts (or by Author) with WordPress Shortcode

Display the Total Number of Scheduled, Draft, or Published Posts (or by Author) with WordPress Shortcode

A number of years ago I published a one-line shortcode that would publish the total number of published WordPress posts with shortcode (using wp_count_posts() ). Since then I've obviously had the need for more features. The code on this page will accomplish the following:

  • Display the total number of queried articles by all or a single authors.
  • Filter by post status, tag, category, or post type.
  • Display the number of posts by an author (or a combination of authors) in the last number of days.
  • Display the number of (filtered) posts in a date range.

All the results are cached to avoid the overhead with repeated queries.

The Result

Following are examples of how the shortcode might be used.

User Posts

Using the shortcode of [numberposts author="marty"] I can return the result of my own published posts. The result: 575. To display the number of scheduled posts for a user, include status="future" to the shortcode with a result of 0. The show the number of my draft posts, the shortcode of [numberposts author="marty" status="draft"] is used with a result of 38.

To include the total posts by multiple authors, include them in a comma delimited list as follows: [numberposts status="publish" author="marty,3"] (note I've included login names and user IDs).

Total Posts

To return the total number of published articles you should omit the author parameter. Shortcode of [numberposts]) returns 575.

Date Range

We can display the number of posts published (or other posts with the use of available attributes) prior to today with the shortcode of [numberposts author="marty" days="28"] with a result of 0.

You may return the number of posts between two dates with the following: [numberposts author="marty" from="1st June 2017" before="15th June 2017"]. In this case, the result is 30. You may optionally use one or the other (before or after). If you specify either with the days attribute, the date as just described will be ignored.

Scheduled (Future) Posts

To display only the number of scheduled posts for all users we should use [numberposts status="future"]. The result: 0.

The Shortcode Function

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Display the Total Number of Scheduled, Draft, or Published Posts (or by Author) with WordPress Shortcode
4
 http://www.beliefmedia.com/count-posts
5
*/
6
 
7
function beliefmedia_count_posts($atts) {
8
 
9
  $atts = shortcode_atts(array(
10
    /* https://codex.wordpress.org/Post_Types (publish, future, draft, page, attachment) */
11
    'status' => 'publish',
12
    'author' => false,
13
    'category' => false,
14
    'tags' => false,
15
 
16
    /* Date */
17
    'days' => false,
18
    'after' => false,
19
    'before' => false,
20
 
21
    /* Cache */
22
    'cache' => 3600 * 6
23
  ), $atts);
24
 
25
 $transient = 'bmnp_' . md5(serialize($atts));
26
 $cachedposts = get_transient($transient);
27
 
28
 if ($cachedposts !== false) {
29
 return $cachedposts;
30
 
31
 } else {
32
 
33
    global $post;
34
 
35
    /* Days is used ahead of dates */
36
    if ($atts['days'] !== false) { $atts['after'] = (boolean) false; $atts['before'] = (boolean) false; }
37
 
38
    /* Generally use this shortcode for random posts */
39
    $post_status = explode(',', $atts['status']);
40
 
41
    $args = array(
42
        'post_type' => 'post',
43
        'post_status' => $post_status,
44
        'posts_per_page' => -1
45
    );
46
 
47
    /* Get user ID from login username */
48
    if ($atts['author'] !== false) {
49
 
50
      /* Array of authors */
51
      $atts['author'] = explode(',', $atts['author']);
52
 
53
        /* If not numeric, get ID */
54
        foreach ($atts['author'] AS $authors) {
55
          if (!is_numeric($authors)) {
56
            $author_ob = get_user_by( 'login', $authors );
57
            $author .= $author_ob->ID . ',';
58
          } else {
59
            $author .= $authors . ',';
60
          }
61
        }
62
 
63
     /* Return string of authors */
64
     $atts['author'] =  rtrim($author, ',');
65
    }
66
 
67
    /* Limit authors? */
68
    if ($atts['author'] !== false) $args['author'] = $atts['author'];
69
 
70
    /* Specific categories? */
71
    if ($atts['category'] !== false) $args['cat'] = $atts['category'];
72
 
73
    /* Specific tags? */
74
    if ($atts['tags'] !== false) $args['tag_id'] = $atts['tags'];
75
 
76
    /* Days before today? */
77
    if ($atts['days'] !== false) {
78
            $after = date('F jS, Y', time() - ($atts['days'] * 86400));
79
            $args['date_query'] = array('after' => $after);
80
    }
81
 
82
    /* Date from .. */
83
    if ( ($atts['after'] !== false) && (strtotime($atts['after']) !== false) ) {
84
            $args['date_query']['after'] = date('F jS, Y', strtotime($atts['after']));
85
    }
86
 
87
    /* Date before .. */
88
    if ( ($atts['before'] !== false) && (strtotime($atts['before']) !== false) ) {
89
            $args['date_query']['before'] = date('F jS, Y', strtotime($atts['before']));
90
    }
91
 
92
    /* Query */
93
    $pages = new WP_query($args);
94
 
95
    /* Build result */
96
    if ($pages->have_posts()) :
97
 
98
        $output = count($pages->posts);
99
 
100
    else :
101
 
102
        $output = '0';
103
 
104
    endif;
105
 
106
   /* Set transient data */
107
   set_transient($transient, $output, $atts['cache']);
108
   return $output;
109
 
110
   /* Reset query */
111
   wp_reset_postdata();
112
 
113
   }
114
 
115
}
116
add_shortcode('numberposts', 'beliefmedia_count_posts');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

status

The status of the post. Normally publish, future, draft, or page. Custom post types may be used. See a full list here .

author

The author is either the login name or the user ID. Multiple may be used.

category

Returns a count of posts by category.

tags

Returns a count of posts by tags type. Use one or more.

days

The days attribute is the number of days prior to today. For example, to count only the number of posts published in the last 7 days, use days="7". For one month, use days="28", and so on.

after

To count the number of posts after a specific date, use after="2nd June 2017". Accepts a strtotime()-compatible string.

after

To count the number of posts before a specific date, use before="15th June 2017". Accepts a strtotime()-compatible string.

cache

The cache is the amount of time to store the results in your database. It caches for 6 hours by default.

Considerations

  • See also: Render future posts in a readable list.
  • The wp_query functions return enormous amounts of information. We've written the function to filter the most common parameters. If you require additional filtration, let us know and we'll update the code.

Download


Title: Display the Total Number of WP Posts (WordPress Plugin)
Description: Display the Total Number of Scheduled, Draft, or Published Posts (or by Author) with WordPress Shortcode.
  Download • Version 0.2, 2.0K, zip, Category: WordPress Plugins (General)
WordPress Shortcodes, (1.4K)    

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment