在遇到内存执行问题时,对brasofilo的示例进行了一些调整;其中一个可能与switch_to_blog memory leak 这已经影响了网站switch_to_blog
调用(加载此仪表板小部件时,我们通常会运行大约1000次。)即使内存限制为256MB+;仍在获取执行错误。修复程序正在添加wp_cache_flush();
可能很粗糙,但清理的内存足以让它执行。其他更改还包括一些逻辑,以避免显示只有1个帖子的站点(可能是默认的),并显示包含2个以上帖子的“活动”站点总数,摘要位于表的底部。
add_action( \'wp_network_dashboard_setup\', \'wpse_66963_network_dashboard_setup\' );
function wpse_66963_network_dashboard_setup()
{
wp_add_dashboard_widget(
\'wpse_66963_posts_count_widget\',
\'<div id="icon-edit" class="icon32"></div><h2>Network Posts Count</h2>\',
\'wpse_66963_posts_count\' );
}
function wpse_66963_posts_count()
{
global $wpdb;
$blogs = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM {$wpdb->blogs} WHERE spam = \'0\'
AND deleted = \'0\' AND archived = \'0\'
ORDER BY registered DESC, 2", ARRAY_A ) );
$original_blog_id = get_current_blog_id();
if ( empty( $blogs ) )
{
echo \'<p>No blogs!</p>\';
break;
}
?>
<table class="widefat">
<thead>
<tr>
<th>Site</th>
<th>Total posts</th>
<th>Draft posts</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Site</th>
<th>Total posts</th>
<th>Draft posts</th>
</tr>
</tfoot>
<tbody>
<?php
$args = array(
\'numberposts\' => -1,
\'post_type\' => \'post\',
\'post_status\' => \'publish\' );
$total_network = $draft_network = 0;
$total_sites = 0;
foreach ($blogs as $blog)
{
wp_cache_flush();
switch_to_blog( $blog->blog_id );
$args[\'post_status\'] = \'publish\';
if (count(get_posts($args))<2) { continue; }
$total_posts = count( get_posts( $args ) );
$total_network += $total_posts;
$total_sites += 1;
$args[\'post_status\'] = \'draft\';
$draft_posts = count( get_posts( $args ) );
$draft_network += $draft_posts;
?>
<tr>
<td><a href="<?php echo site_url(); ?>"><?php echo site_url(); ?></a></td>
<td><?php echo $total_posts; ?></td>
<td><?php echo $draft_posts; ?></td>
</tr>
<?php
}
?>
<tr>
<td><b>Total count (<?php echo $total_sites;?> sites with content)</b></td>
<td><?php echo $total_network; ?></td>
<td><?php echo $draft_network; ?></td>
</tr>
</tbody>
</table>
<?php echo memory_get_usage(); ?>
<br/>
<?php echo memory_get_peak_usage(); ?>
<?php
switch_to_blog( $original_blog_id );
}