wordpresswidgetwordpress-jetpack

Exclude pages from Jetpack's "Top Posts & Pages" widget


I have the following scenario. (WordPress with Jetpack)

Certain "custom" pages only display something if data (e.g. search term) is provided. If not, the pages are normally "blank". As they are being accessed (via link including query vars) they are accounted for in the stats. But... If you click them under "Top Posts & Pages" (widget) they are just blank.

Is there a way to not list those specific pages under "Top Posts & Pages"? Or can I maybe redirect the stats from a subpage to a parent page?

Thanks in advance


Solution

  • You can hook into jetpack_widget_get_top_posts to exclude these pages from the Top Posts & Pages widget.

    Add the following code to your theme's functions.php file:

    function wp653886_exclude_from_top_posts( $posts, $post_ids, $count ) {
    
        $page_ids_to_exclude = array( 144, 764, 876 ); // Put here the IDs of the pages you wish to exclude.
    
        foreach ( $posts as $k => $post ) {
            // Remove this item from the list
            if ( in_array( $post['post_id'],  $page_ids_to_exclude ) ) {
                unset( $posts[$k] );
            }
        }
    
        return $posts;
    
    }
    add_filter( 'jetpack_widget_get_top_posts', 'wp653886_exclude_from_top_posts', 10, 3 );
    

    Edit the $page_ids_to_exclude array to add the IDs of the pages you want to exclude from the widget and you're good to go.