在WordPress主题中添加自定义侧边栏的步骤如下:
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' );
以上代码中,register_sidebar函数会在Widgets页面中添加一个名为“Custom Sidebar”的侧边栏。
在主题的侧边栏代码中,将原有的侧边栏代码替换为以下代码:
<?php if ( is_active_sidebar( 'custom_sidebar' ) ) : ?>
<div id="secondary" class="widget-area" role="complementary">
<?php dynamic_sidebar( 'custom_sidebar' ); ?>
</div><!-- #secondary -->
<?php endif; ?>
示例代码说明:
此示例代码中,添加了名为“Custom Sidebar”的侧边栏,并将其添加到了主题的侧边栏位置。若想要添加其他名称的侧边栏,只需要修改register_sidebar函数中的“name”和“id”参数即可。