WordPress增加自定义边栏数量并实现文章、页面个性化选择

  • Comments Off on WordPress增加自定义边栏数量并实现文章、页面个性化选择
  • 144
  • A+
所属分类:WordPress主题

首先在主题functions.php文件添加以下代码,注册新sidebar。

function custom_register_sidebars() {
    // 注册额外的侧边栏,可以根据需要修改数量
    register_sidebar(array(
        'name'          => __('Custom Sidebar 1'),
        'id'            => 'custom_sidebar_1',
        'description'   => __('This is a custom sidebar.'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ));

    register_sidebar(array(
        'name'          => __('Custom Sidebar 2'),
        'id'            => 'custom_sidebar_2',
        'description'   => __('This is another custom sidebar.'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ));

    // 添加更多自定义侧边栏...
}
add_action('widgets_init', 'custom_register_sidebars');

有的主题已经支持自定义边栏,就可以直接选择了。如果主题文件已经按照文章、页面固定了边栏,规范写法是引用边栏的ID,需要在文章和页面添加一个自定义字段如sidebar,然后修改主题对应的代码,一般为sidebar.php即可,示例代码如下。

<?php
// 获取当前文章或页面的侧边栏选择
$selected_sidebar = get_post_meta(get_the_ID(), 'sidebar', true);

if ($selected_sidebar) {
    dynamic_sidebar($selected_sidebar);
} else {
    // 如果没有选择特定侧边栏,则显示默认侧边栏
    dynamic_sidebar('default_sidebar');
}
?>
weinxin
独角兽驿站
公众号