使用您的原始代码,我将查询/计数/缓存代码拉到一个单独的函数中。我还没有机会测试这些,所以如果您遇到任何错误,我深表歉意。如果你这样做了,请在这里发布,我会在测试时更新。
简单地说,想法是首先根据每个值唯一的键(名称)检查有效的瞬态,如果不存在值,则重新创建并存储它。无论哪种方式,调用函数都应返回posttype
帖子,最长4小时。
我随机选择了4个小时,但这是一个容易编辑的参数。只要想出一些东西来代替“你的临时钥匙”,你就可以很好地使用了。
add_action( \'admin_menu\', \'add_cpt_menu_bubble\' );
function add_cpt_menu_bubble() {
global $menu;
// Retrieve cached value or count current number of posttype posts.
$count_posts = wpse_count_of_posttype_posts
// only display the number of pending posts over a certain amount
if ( $count_posts > 5 ) {
foreach ( $menu as $key => $value ) {
if ( $menu[$key][2] == \'edit.php?post_type=custom_post_type_name\' ) {
$menu[$key][0] .= \' <span class="update-plugins count-2"><span class="update-count">\' . $count_posts . \'</span></span>\';
return;
}
}
}
}
function wpse_count_of_postype_posts() {
// First try to get a cached value
if ( false === ( $num_posts = get_transient( \'your-transient-key\' ) ) ) {
// this code runs when there is no valid transient set
// Your original query args
$args = array(
\'order\' => \'DESC\',
\'posts_per_page\' => \'-1\',
\'post_type\' => \'custom_post_type_name\',
\'custom_tax_name\' => \'pending-review\'
);
// Instantiate WP_Query instead
$posttype_query = new WP_Query( $args );
// One of the properties of the class is a count of the posts. No need to loop and increment a counter
// https://codex.wordpress.org/Class_Reference/WP_Query#Properties
$num_posts = $posttype_query->post_count;
// Store the count in your transient; build it now for the future https://www.youtube.com/watch?v=XjYLvpwDNOY
set_transient( \'your-transient-key\', $num_posts, 4 * HOUR_IN_SECONDS );
return $num_posts;
}
}