从特定页面删除特定窗口小部件

时间:2019-05-09 13:49:42

标签: wordpress

我有特定的页面,需要从侧边栏隐藏特定的窗口小部件。我有

-5个本应仅显示nav_menu-1的页面

-6应该仅显示nav_menu-2

的其他页面

-然后所有应该只显示nav_menu-3的单帖

我有这个代码

add_filter( 'widget_display_callback', 'widget_display_2', 50, 3 );
function widget_display_2( $instance, $widget, $args ){
if ( is_single() && $widget->id == 'nav_menu-1' ) {
    return false;
}
return $instance;
}

但是插入所有页面和小部件ID来实现目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

这听起来很奇怪,但是为什么不使用三个不同的侧边栏并按条件调用它们呢?这样,您的主题将变得更加灵活。将其硬编码到主题或插件中总是很不好的。

// Register Sidebars
function custom_sidebars() {

$args = array(
    'id'            => 'custom-sidebar-1',
    'name'          => __( 'Custom Sidebar 1', 'text_domain' ),
);
register_sidebar( $args );

$args = array(
    'id'            => 'custom-sidebar-2',
    'name'          => __( 'Custom Sidebar 2', 'text_domain' ),
);
register_sidebar( $args );

$args = array(
    'id'            => 'custom-sidebar-3',
    'name'          => __( 'Custom Sidebar 3', 'text_domain' ),
);
register_sidebar( $args );

}
add_action( 'widgets_init', 'custom_sidebars' );

...将其添加到functions.php后,您可以使用条件函数调用不同的侧边栏。

<?php
/** call custom sidebar on single.php template **/
if ( is_single() ){
dynamic_sidebar( 'custom-sidebar-1' );
}
?>

<?php
/** call custom sidebar on page.php template (all pages) **/
if ( is_page() ){
dynamic_sidebar( 'custom-sidebar-2' );
}
?>

<?php
/** call custom sidebar on multiple pages by id **/
if ( is_page( array( 11, 22, 33, 44 ) ) ){
dynamic_sidebar( 'custom-sidebar-3' );
}
?>