首页 问答 正文

如何在WordPress中为单个页面设置自定义侧边栏?

注册会员 / 悠然自学 / 2023-06-11/ 浏览 135 次

在WordPress中为单个页面设置自定义侧边栏可以通过以下步骤实现:

  1. 首先需要创建一个自定义侧边栏。可以在主题的functions.php文件中添加以下代码:
function custom_sidebar() {
    register_sidebar( array(
        'name'          => __( 'Custom Sidebar', 'textdomain' ),
        'id'            => 'custom-sidebar',
        'description'   => __( 'Add widgets here to appear in your custom sidebar.', 'textdomain' ),
        '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', 'custom_sidebar' ); 

这将在WordPress后台的小工具中注册一个名为“Custom Sidebar”的自定义侧边栏。

  1. 创建一个新的页面或编辑一篇已存在的页面。在编辑页面的右侧边栏中,可以看到一个名为“页面属性”的部分。在这个部分,找到一个名为“模板”的下拉菜单。

  2. 选择一个名为“Custom Page with Sidebar”的自定义页面模板。这需要在主题目录的根目录中创建一个新的文件custom-page-with-sidebar.php,并在文件中添加以下代码:

<?php
/**
 * Template Name: Custom Page with Sidebar
 */

get_header(); ?>

<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">

        <?php while ( have_posts() ) : the_post(); ?>

            <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <header class="entry-header">
                    <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
                </header><!-- .entry-header -->

                <div class="entry-content">
                    <?php the_content(); ?>
                </div><!-- .entry-content -->
            </article><!-- #post-## -->

        <?php endwhile; // end of the loop. ?>

    </main><!-- #main -->
</div><!-- #primary -->

<?php get_sidebar( 'custom' ); ?>
<?php get_footer(); ?> 

在这个文件中,可以定义页面布局并调用自定义侧边栏。

  1. 在页面编辑器中添加所需的小部件到新创建的“Custom Sidebar”自定义侧边栏中。可以在WordPress后台的小工具中添加小部件,然后将它们拖放到自定义侧边栏中。这些小部件将出现在所选页面的侧边栏中。

以上就是在WordPress中为单个页面设置自定义侧边栏的步骤。需要注意更新WordPress主题文件以使更改生效。

大家谈论
    我的见解