在WordPress中,register_sidebar()
和 dynamic_sidebar()
是两个用于创建和管理侧边栏的函数。下面是如何使用这两个函数的步骤:
1. 注册侧边栏
首先,你需要使用 register_sidebar()
函数来注册一个新的侧边栏。这通常在主题的 functions.php
文件中完成。
以下是一个基本的 register_sidebar()
函数示例:
function my_custom_sidebars() {
// 注册一个新的侧边栏
register_sidebar(
array(
'name' => '我的自定义侧边栏', // 侧边栏的名称
'id' => 'my_custom_sidebar', // 侧边栏的唯一ID
'description' => '这是我的自定义侧边栏描述', // 侧边栏的描述
'before_widget' => '<div id="%1$s" class="widget %2$s">', // 小工具的开始标签
'after_widget' => '</div>', // 小工具的结束标签
'before_title' => '<h2 class="widgettitle">', // 小工具标题的开始标签
'after_title' => '</h2>' // 小工具标题的结束标签
)
);
}
// 在 WordPress 初始化过程中添加侧边栏
add_action( 'widgets_init', 'my_custom_sidebars' );
2. 显示侧边栏
一旦侧边栏被注册,你可以在主题的任何位置使用 dynamic_sidebar()
函数来显示它。通常,这会在主题的模板文件中完成,例如 sidebar.php
。
以下是如何使用 dynamic_sidebar()
函数的示例:
<?php
if ( is_active_sidebar( 'my_custom_sidebar' ) ) {
dynamic_sidebar( 'my_custom_sidebar' );
}
?>
这段代码首先检查 my_custom_sidebar
是否有活动的小工具(即是否有小工具被添加到侧边栏中)。如果有,它将调用 dynamic_sidebar()
函数来显示所有添加到该侧边栏的小工具。
完整的示例
以下是结合上述两步的完整示例:
- 在
functions.php
文件中注册侧边栏:
function my_custom_sidebars() {
register_sidebar(
array(
'name' => '我的自定义侧边栏',
'id' => 'my_custom_sidebar',
'description' => '这是我的自定义侧边栏描述',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
)
);
}
add_action( 'widgets_init', 'my_custom_sidebars' );
- 在
sidebar.php
文件中显示侧边栏:
<?php if ( is_active_sidebar( 'my_custom_sidebar' ) ) : ?>
<?php dynamic_sidebar( 'my_custom_sidebar' ); ?>
<?php endif; ?>
这样,当你在WordPress后台的“外观” > “小工具”部分将小工具添加到“我的自定义侧边栏”时,它们将在你的网站上相应地显示出来。