如何让WordPress 让主题支持Widget(侧边栏小工具)

单侧边栏

functions.php

<?php
if( function_exists('register_sidebar') ) {
    register_sidebar(array(
        'before_widget' => '<li>', // widget 的开始标签
        'after_widget' => '</li>', // widget 的结束标签
        'before_title' => '<h3>', // 标题的开始标签
        'after_title' => '</h3>' // 标题的结束标签
    ));
}
?>

sidebar.php

<div id="sidebar">
    <ul>
<?php // 如果没有使用 Widget 才显示以下内容, 否则会显示 Widget 定义的内容
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) :
?>
    <!-- widget 1 -->
    <li>
        <h3>标题 1</h3>
        <ul>
            <li>条目 1.1</li>
            <li>条目 1.2</li>
            <li>条目 1.3</li>
        </ul>
    </li>
    <!-- widget 2 -->
    <li>
        <h3>标题 2</h3>
        <ul>
            <li>条目 2.1</li>
            <li>条目 2.2</li>
            <li>条目 2.3</li>
        </ul>
    </li>
<?php endif; ?>
    </ul>
</div>

双侧边栏

functions.php

<?php
if( function_exists('register_sidebar') ) {
    register_sidebar(array(
        'name' => 'Sidebar_1', // 侧边栏 1 的名称
        'before_widget' => '<li>', // widget 的开始标签
        'after_widget' => '</li>', // widget 的结束标签
        'before_title' => '<h3>', // 标题的开始标签
        'after_title' => '</h3>' // 标题的结束标签

    ));

    register_sidebar(array(
        'name' => 'Sidebar_2', // 侧边栏 2 的名称
        'before_widget' => '<li>', // widget 的开始标签
        'after_widget' => '</li>', // widget 的结束标签
        'before_title' => '<h3>', // 标题的开始标签
        'after_title' => '</h3>' // 标题的结束标签

    ));
}
?>

sidebar.php

<div id="sidebar_1">
    <ul>
<?php // 如果没有在侧边栏 1 中使用 Widget 才显示以下内容, 否则会显示 Widget 定义的内容
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar_1') ) :
?>
    <!-- widget 1 -->
    <li>
        <h3>标题 1</h3>
        <ul>
            <li>条目 1.1</li>
            <li>条目 1.2</li>
            <li>条目 1.3</li>
        </ul>
    </li>
<?php endif; ?>
    </ul>
</div>

<div id="sidebar_2">
    <ul>
<?php // 如果没有在侧边栏 2 中使用 Widget 才显示以下内容, 否则会显示 Widget 定义的内容
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar_2') ) :
?>
    <!-- widget 2 -->
    <li>
        <h3>标题 2</h3>
        <ul>
            <li>条目 2.1</li>
            <li>条目 2.2</li>
            <li>条目 2.3</li>
        </ul>
    </li>
<?php endif; ?>
    </ul>
</div>
原文地址:https://www.cnblogs.com/wpxuexi/p/6386025.html