Is there a way to get post count for all active sites on a multisite, using WP-CLI? Conceptually, I'm looking for a combination of wp post list --format=count
and wp site list --format=count
but I don't think that's feasible.
-
1The wp-cli has no function for this goal. Maybe you create a custom function, like wordpress.stackexchange.com/questions/294401/…– bueltgeMar 31 at 13:26
-
1you could grab it for each site then use addition, you don't have to do everything in a single command, likewise bash can do loops. There is no need to write custom WP CLI commands or PHP code– Tom J Nowell ♦Mar 31 at 14:05
2 Answers
Conceptually, I'm looking for a combination of wp post list --format=count and wp site list --format=count but I don't think that's feasible.
Nope, such a command does not exist, but adding it would be wasteful and counterproductive.
Just because there isn't a dedicated single tool that builds a house all at once doesn't mean tools don't exist, or that you can't build houses.
It's the same here. Multiple commands combined together can give you what you want.
For example that is no command that will print out the name of all active blogs, and yet something similar to these commands will do that:
blogs=$(wp site list --fields="url" --format="csv")
for url in $blogs
do
wp option get blogname --url="${url}"
done
Note that the above is standard bash scripting, it's not unique to WordPress.
Likewise storing the post count in a variable with COUNT=$(wp ..... )
, and adding 2 variables together with basic addition using num=$((num1 + num2))
should give you the missing pieces to complete what you want and get a count that includes all posts across a multisite.
Since this isn't something wp-cli
can handle out of the box, you can write a simple script that'll do it for you.
<?php
$sites = get_sites( [ 'number' => 10000 ] );
$count = 0;
foreach ( $sites as $site ){
switch_to_blog( $site->blog_id );
$count += wp_count_posts()->publish;
restore_current_blog();
}
echo $count . PHP_EOL;
Save this code as a file, eg count-posts.php
, and then run it using wp-cli
's eval-file
command:
wp eval-file count-posts.php
This will count all the published posts in all the sites in your Multisite network (as long as you've got less than 10,000 sites; if you've got more, adjust the 'number' => 10000
argument to suit).