您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
4-42. 边栏工具功能详解
发布时间:2023-03-23 18:14:14编辑:雪饮阅读()
上篇了解了wp_nav_menu的参数,那么对于边栏功能实际上和这个wp_nav_menu是差不多的。且也是支持多个边栏的注册(需要执行多次边栏注册方法)。如果在functions.php中完成了边栏注册,则在wordpress后台就会有小工具进去可以看到我们注册的边栏。
并且可以手动将系统已经有的小工具拖拽至自己定义的边栏里面并在你的边栏里面为该小工具自定义名称。
在functions.php中注册的函数是register_sidebar,一般的挂钩于widgets_init钩子。
然后注册参数什么的和上篇一样,基本上就是见名知意了,或者你可以调整参数值,就可以在页面中查看到效果。
然后边栏需要在模板中调用时候也可以使用dynamic_sidebar方法,其接参即为边栏id
然后由于侧边栏有时候你没有配置,或者说不小心删除了,或者即便有侧边栏,但是该侧边栏里面没有小部件的时候,则就没有什么东西可以调用,为了用户体验,一般比如可以提示下“抱歉,xxx暂无数据”之类的话语,所以这里则就需要判断下当前要使用的侧边栏的可用性,则是可用通过函数is_active_sidebar来判断了。
接下来那么具体到functions.php的实现如:
<?php
function myfunc001(){
register_sidebar([
'name' => '边栏1',
'id' => "sidebar-1",
'description' => '第一个边栏',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => "</li>\n",
'before_title' => '<h2 class="widgettitle">',
'after_title' => "</h2>\n",
]);
register_sidebar([
'name' => '边栏2',
'id' => "sidebar-2",
'description' => '第二个边栏',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => "</li>\n",
'before_title' => '<h2 class="widgettitle">',
'after_title' => "</h2>\n",
]);
}
add_action('widgets_init','myfunc001');
?>
那么一般的调用这里假定是index.php则如
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php wp_head();?>
</head>
<body>
<h1>边栏001</h1>
<div style="border:1px solid pink;">
<?php if(is_active_sidebar('sidebar-1')):?>
<?php dynamic_sidebar('sidebar-1');?>
<?php else:?>
该边栏无效(可能是没有该边栏,或者该边栏还没有添加任何边栏工具吧)
<?php endif;?>
</div>
<h1>边栏002</h1>
<div style="border:1px solid pink;">
<?php if(is_active_sidebar('sidebar-2')):?>
<?php dynamic_sidebar('sidebar-2');?>
<?php else:?>
该边栏无效(可能是没有该边栏,或者该边栏还没有添加任何边栏工具吧)
<?php endif;?>
</div>
</body>
</html>
关键字词:边栏,工具
下一篇:4-43. 开启特色图像功能