2

Without using a plugin, how do I prevent/exclude the sidebar widget "recent posts" from showing up on the home/front page?

I do want it to show on the sidebar of rest of other archive/post pages.

4
  • @ Sumit Yes, I used it as a reference with minor modification to solve my problem. Yet not sure if there's a better way of making string comparison of the widget.
    – KDX
    May 15, 2016 at 20:21
  • Sorry did not get you by comparison of the widget ?
    – Sumit
    May 16, 2016 at 6:23
  • @Sumit Currently it's using strncmp( $widget_id, 'recent-posts', 12 ) string comparison for checking widget name. Was wondering if there's a better way, as the original author of the code mentioned.
    – KDX
    May 17, 2016 at 0:11
  • 1
    Please check I have added another way wordpress.stackexchange.com/a/226924/32475 which I think is better.
    – Sumit
    May 17, 2016 at 15:20

1 Answer 1

0

I've found the exact solution to my question here:

https://wordpress.stackexchange.com/a/17687/92505

Here's the exact code I used after some modification to make it work on my situation.

Add the following code to functions.php where 'sidebar-1' is your sidebar ID.

'recent-posts' is the name of the widget your want yo hide.

12 is the length of the string 'recent-posts'

Hope someone may find it useful.

add_filter( 'sidebars_widgets', 'wpse17681_sidebars_widgets' );
function wpse17681_sidebars_widgets( $sidebars_widgets )
{
    if ( is_home() || is_front_page() /* Or whatever */ ) {
        foreach ( $sidebars_widgets as $sidebar_id => &$widgets ) {
            if ( 'sidebar-1' != $sidebar_id ) {
                continue;
            }
            foreach ( $widgets as $idx => $widget_id ) {
                // There might be a better way to check the widget name
                if ( 0 === strncmp( $widget_id, 'recent-posts', 12 ) ) {
                    unset( $widgets[$idx] );
                }
            }
        }
    }

    return $sidebars_widgets;
}
3
  • 1
    You could always just go with CSS and target the body class for any post type etc. I have added several unique body classes for this exact reason. It can be used to limit visibility to any post type, user / non-user, user-role, if other stuff is visible etc. May 16, 2016 at 0:17
  • @Jarmerson You meant setting display to none for the widget block when certain condition is met?
    – KDX
    May 16, 2016 at 3:26
  • 1
    Yes. So the body class on the home page would include home and you would append .home to the CSS to display none on the home page. May 16, 2016 at 3:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.