我试图显示我的WordPress多站点的帖子总数。为此,我使用了下面的代码,它在一开始就起作用了。所以我想set_site_transient
应该将输出缓存一段时间。
也许有人知道我的错误是什么。我找不到解决办法。
干杯,非常感谢!
function posts_count_func( $args ){
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();
$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\';
}
set_site_transient ( \'total_posts_cache\', $total_network, 24 * HOUR_IN_SECONDS );
switch_to_blog( $original_blog_id );
}
function posts_shortcode_count_func( $atts ){
return get_site_transient( \'total_posts_cache\' );
}
add_shortcode( \'posts\', \'posts_shortcode_count_func\' );
最合适的回答,由SO网友:Pat J 整理而成
你好像没打电话posts_count_func()
任何地方,所以如果您的瞬态过期,它不会被重置。
function posts_shortcode_count_func( $atts ){
$post_count = get_site_transient( \'total_posts_cache\' );
if( ! $post_count ) {
posts_count_func();
$post_count = get_site_transient( \'total_posts_cache\' );
}
return $post_count;
}
add_shortcode( \'posts\', \'posts_shortcode_count_func\' );
根据
docs for get_transient()
(这是的非网络版本
get_site_transient()
),
false
如果瞬态不存在或已过期,则返回。
Also: 你不应该$args[\'post_status\'] = \'publish\';
在您的foreach()
循环,因为您已经在$args
向上排列更高。