【问题标题】:Show balloon notification when there are new posts有新帖子时显示气球通知
【发布时间】:2018-10-25 10:44:29
【问题描述】:

我正在 wordpress 中添加带有 wp_insert_post 的帖子。我想显示这样的气球通知

当管理员来到仪表板时。并在管理员查看帖子后删除通知。

【问题讨论】:

    标签: wordpress


    【解决方案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' );
    

    自己测试过:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多