有新帖子时显示气球通知

时间:2018-10-25 10:44:30

标签: wordpress

我在wordpress中添加带有wp_insert_post的帖子。我想显示气球通知 enter image description here

当管理员进入信息中心时。并在管理员查看帖子后删除通知。

1 个答案:

答案 0 :(得分:1)

如果管理员查看了编辑帖子页面,请钩住init并添加帖子元数据。然后钩住admin_menu并查询元键_viewed_by_admin 存在的所有帖子。最后,将未读帖子计数气泡添加到菜单项标题。

function admin_viewed_post() {

    global $pagenow;

    // Check if we are on the post edit page.
    if ( $pagenow === 'post.php' && isset( $_GET[ 'post' ] ) && get_post_type( $_GET[ 'post' ] ) === 'post' ) {

        // Check if the user viewing the page is an admin.
        if ( is_admin() ) {

            $post_id = $_GET[ 'post' ];

            // Check if the meta data already exists.
            if ( ! metadata_exists( 'post', $post_id, '_viewed_by_admin' ) ) {

                add_post_meta( $post_id, '_viewed_by_admin', true, true );
            }
        }
    }
}

add_action( 'init', 'admin_viewed_post' );


function add_posts_unread_count_bubble() {

    global $menu;

    // Find the key of menu item 'Posts' in the menu array.
    foreach( $menu as $key => $menu_item ) {

        // Check if current $menu_item[ 5 ] equals 'menu-posts'.
        if ( $menu_item[ 5 ] === 'menu-posts' ) {

            // Check if index exists in $menu.
            if( isset( $menu[ $key ] ) ) {

                $menu_key = $key;
                break; 
            }
        }
    }

    // Return if the menu key was not found.
    if( ! $menu_key ) {
        return;
    }

    // Count all the posts that are unread by admin.
    $query_args = array(
        'posts_per_page' => -1,
        'post_type'      => 'post',
        'meta_query'     => array(
            // Query all posts where meta key '_viewed_by_admin' does not exist.
             array(
                'key'     => '_viewed_by_admin',
                'compare' => 'NOT EXISTS',
            ),
        ),
    );

    $query = new WP_Query( $query_args );
    $unread_post_count = $query->post_count;

    // Return if unread post count equals 0.
    if( $unread_post_count === 0 ) {
        return;
    }

    // Add the unread posts count bubble to the menu item.
    $menu[ $menu_key ][ 0 ] .= sprintf( ' <span class="update-plugins"><span class="plugin-count">%1$s</span></span>', $unread_post_count );
}

add_action( 'admin_menu', 'add_posts_unread_count_bubble' );

我自己测试过:unread post count