phpwordpresscustomizationwp-admin

How do I check or count post "draft" status and display bubble next to the menu in wordpress


So thanks to rudrastyh I was able to get the main part of the code that will enable the notification bubbles but don't have any way yet of checking and counting the Testimonials in draft status only (and displaying count in the bubble) I am very green at php and if someone can provide an answer would be so grateful - thanks in advance!

// ADD BUBBLES TO ADMIN_COOKIE_PATH

add_action( 'admin_menu', function() {

    global $menu;

    $count = 5;

    $menu_item = wp_list_filter(
        $menu,
        array( 2 => 'edit.php?post_type=testimonials' ) // 2 is the position of an array item which contains URL, it will always be 2!
    );

    if ( ! empty( $menu_item )  ) {
        $menu_item_position = key( $menu_item ); // get the array key (position) of the element
        $menu[ $menu_item_position ][0] .= ' <span class="awaiting-mod">' . $count . '</span>';
    }

});

enter image description here


Solution

  • Try this

    add_action( 'admin_menu', function() {
    
        global $menu;
    
        //$count = 5;
        $args = array(
            'numberposts'   => -1,
            'post_type'     => 'testimonials',
            'fields' => 'ids',
            'no_found_rows' => true,
            'post_status'   => array( 'draft' ),
    
        );
        $count_drafts = count( get_posts( $args ) ); 
        if($count_drafts > 0) {
      
        $menu_item = wp_list_filter(
            $menu,
            array( 2 => 'edit.php?post_type=testimonials' ) // 2 is the position of an array item which contains URL, it will always be 2!
        );
    
        if ( ! empty( $menu_item )  ) {
            $menu_item_position = key( $menu_item ); // get the array key (position) of the element
            $menu[ $menu_item_position ][0] .= ' <span class="awaiting-mod">' . $count_drafts . '</span>';
        }
        }
    });
    

    Important detail, we use in the query

    'fields' => 'ids',
    'no_found_rows' => true,
    

    because we only need to calculate the count, its significantly reduces the load on the database and speeds up the query