問題描述

很像 「外掛」 或 「評論」 選單項在氣泡中有如下更新和未修改的註釋的通知,我想使用該氣泡來顯示具有”Pending review” 狀態的 CPT 數量。怎麼去做這個?

我發現 this thread,但不太確定從那裡去哪裡。

那會是整齊的因為我需要使用 user-generated 內容 (自定義帖子型別) 的網站上的此功能。每當使用者提交新的 CPT 時,其狀態設定為”Pending review”,我想讓網站管理員快速瀏覽選單,檢視需要注意的專案數量。

編輯:我現在有這個程式碼:

// buuble notifications for custom posts with status pending
add_action( 'admin_menu', 'add_pending_bubble' );

function add_pending_bubble() {
    global $menu;

    $custom_post_count = wp_count_posts('custom-post-name');
    $custom_post_pending_count = $custom_post_count->pending;

    if ( $custom_post_pending_count ) {
        foreach ( $menu as $key => $value ) {
            if ( $menu[$key][2] == 'edit.php?post_type=custom-post-name' ) {
                $menu[$key][0] .= ' <span class="update-plugins count-' . $custom_post_pending_count . '"><span class="plugin-count">' . $custom_post_pending_count . '</span></span>';
                return;
            }
        }
    }
}

… 哪些工作,雖然有點不一致。有時顯示,有時不顯示。另外,如果我有多個 CPT,那麼如何對這些 CPT 的每個選單項應用這個程式碼?上述程式碼只能使用一個 CPT 。

最佳解決方案

我做了這個工作,透過一個帖子型別列表進行迭代,並使用輔助功能 (而不是手動迭代 $menu 物件) 來確定帖子型別的正確 $menu 金鑰。

功能參考:get_post_typeswp_count_posts

add_action( 'admin_menu', 'pending_posts_bubble_wpse_89028', 999 );

function pending_posts_bubble_wpse_89028()
{
    global $menu;

    // Get all post types and remove Attachments from the list
    // Add '_builtin' => false to exclude Posts and Pages
    $args = array( 'public' => true );
    $post_types = get_post_types( $args );
    unset( $post_types['attachment'] );

    foreach( $post_types as $pt )
    {
        // Count posts
        $cpt_count = wp_count_posts( $pt );

        if ( $cpt_count->pending )
        {
            // Menu link suffix, Post is different from the rest
            $suffix = ( 'post' == $pt ) ? '' : "?post_type=$pt";

            // Locate the key of
            $key = recursive_array_search_php_91365( "edit.php$suffix", $menu );

            // Not found, just in case
            if( !$key )
                return;

            // Modify menu item
            $menu[$key][0] .= sprintf(
                '<span class="update-plugins count-%1$s" style="background-color:white;color:black"><span class="plugin-count">%1$s</span></span>',
                $cpt_count->pending
            );
        }
    }
}

// http://www.php.net/manual/en/function.array-search.php#91365
function recursive_array_search_php_91365( $needle, $haystack )
{
    foreach( $haystack as $key => $value )
    {
        $current_key = $key;
        if(
            $needle === $value
            OR (
                is_array( $value )
                && recursive_array_search_php_91365( $needle, $value ) !== false
            )
        )
        {
            return $current_key;
        }
    }
    return false;
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。