📜  注册侧边栏 wordpress - PHP (1)

📅  最后修改于: 2023-12-03 14:56:03.588000             🧑  作者: Mango

注册侧边栏 WordPress - PHP

WordPress 是世界上最受欢迎的开源内容管理系统。它提供了很多便于开发者操作的 API,其中包括侧边栏的注册和操作。在这篇文章中,我们将会介绍如何使用 PHP 语言在 WordPress 中注册一个侧边栏。

步骤
1. 在 functions.php 文件中添加以下代码

在 WordPress 主题文件夹中打开 functions.php 文件,并添加以下代码:

function wpb_widgets_init() {

    register_sidebar( array(
        'name' => __( 'Main Sidebar', 'wpb' ),
        'id' => 'sidebar-1',
        'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'wpb' ),
        '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', 'wpb_widgets_init' );

这将注册一个功能强大的侧边栏,其中包括:

  • 名称:Main Sidebar
  • ID:sidebar-1
  • 描述:Widgets in this area will be shown on all posts and pages.
  • Widget 的 HTML 布局:before_widget, after_widget, before_title, after_title
2. 在主题中添加侧边栏

打开你的主题的 sidebar.php 文件,然后添加以下代码来调用侧边栏:

<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>
    <div id="primary-sidebar" class="primary-sidebar widget-area" role="complementary">
        <?php dynamic_sidebar( 'sidebar-1' ); ?>
    </div><!-- #primary-sidebar -->
<?php endif; ?>

这将在你的主题中添加名为 "Main Sidebar" 的侧边栏。

3. 在 WordPress 后台中添加小工具

现在,你已经成功注册了一个侧边栏,在 WordPress 后台中,可以添加小工具并在侧边栏中使用。

结论

恭喜!你已成功使用 PHP 在 WordPress 中注册一个侧边栏并使其可供使用。下一步是在其中添加小工具以完成你的主题。