首页 问答 正文

如何在wordpress主题中添加自定义侧边栏?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 211 次

在WordPress主题中添加自定义侧边栏的步骤如下:

  1. 打开主题的functions.php文件,添加以下代码:
function custom_sidebar() {
    register_sidebar( array(
        'name'          => __( 'Custom Sidebar', 'textdomain' ),
        'id'            => 'custom_sidebar',
        'description'   => __( 'Add widgets here to appear in your custom sidebar.', 'textdomain' ),
        'before_widget' => '<div class="widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'custom_sidebar' ); 
  1. 以上代码中,register_sidebar函数会在Widgets页面中添加一个名为“Custom Sidebar”的侧边栏。

  2. 在主题的侧边栏代码中,将原有的侧边栏代码替换为以下代码:

<?php if ( is_active_sidebar( 'custom_sidebar' ) ) : ?>
    <div id="secondary" class="widget-area" role="complementary">
        <?php dynamic_sidebar( 'custom_sidebar' ); ?>
    </div><!-- #secondary -->
<?php endif; ?> 
  1. 以上代码会判断“Custom Sidebar”侧边栏是否被添加到Widget中,若有,则在侧边栏位置显示此侧边栏。

示例代码说明:

此示例代码中,添加了名为“Custom Sidebar”的侧边栏,并将其添加到了主题的侧边栏位置。若想要添加其他名称的侧边栏,只需要修改register_sidebar函数中的“name”和“id”参数即可。

大家谈论
    我的见解