WordPress企业主题定制/开发/优化

WordPress register_sidebar 自定义边栏支持widgets

首页 » WORDPRESS主题技术 » WordPress register_sidebar 自定义边栏支持widgets

Everyone who is building WordPress Themes probably implement the widget function in their theme. Code for the widgets is in functions.php. Here a code snippet of the default theme:

if ( function_exists('register_sidebar') )
register_sidebar(array(
'before_widget' => '<li id="%1$s">',
'after_widget' => '</li>',
'before_title' => '<h2>',
'after_title' => '</h2>',
));

As we all know, there is the function register_sidebar since version 2.2. My question is: How long do you want to ask if this function exists? The default theme of WordPress 2.7 doesn't ask, if have_comments (a new template tag of version 2.7) exists, but it asks if register_sidebar exists. I just suppose the developers just forgot it and everybody in the world thinks, that it has to be like that.

Please don't misunderstand, the query isn't wrong, but in my opinion just useless in the default theme of version 2.7

Since we are already talking about the register_sidebar and it's use, the code of a premium theme uses this query even 3 times:

<?php
if ( function_exists('register_sidebar') )
register_sidebar(array('name'=>'Home Sidebar',
'before_widget' => '<div>',
'after_widget' => '</div><div></div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
?>
<?php
if ( function_exists('register_sidebar') )
register_sidebar(array('name'=>'Post Sidebar',
'before_widget' => '<div>',
'after_widget' => '</div><div></div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
?>
<?php
if ( function_exists('register_sidebar') )
register_sidebar(array('name'=>'Page Sidebar',
'before_widget' => '<div>',
'after_widget' => '</div><div></div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
?>

This is not really a good example for a premium theme. First, why closing the PHP tag after every function and open it before every function again?
Second, if the function register_sidebar exist in first place, it will also exist the 2nd time
and third, the code is almost identical except the name of the sidebar. That could be done much easier:

<?php
$sidebars = array('Home Sidebar', 'Post Sidebar', 'Page Sidebar');
foreach($sidebars as $name) {
register_sidebar(array('name'=> $name,
'before_widget' => '<div>',
'after_widget' => '</div><div></div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
));
}
?>

As I said, it's not wrong and I didn't mean it as it is a bad way to code, but sometimes you can do it much easier

相关项目

  • WordPress外贸企业主题

  • 最近更新

  • 热门标签