You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何添加仅在WooCommerce商店页面显示的自定义小部件

实现仅商店页面显示专属侧边栏的修复方案

1. 修复functions.php中的注册语法错误

你当前的代码存在语法问题:第二个register_sidebar函数被错误嵌套在了第一个register_sidebar的参数中,会导致商店侧边栏根本没有注册成功,替换为以下正确代码:

function kucuksun_widgets_init() {
    // 注册默认侧边栏
    register_sidebar(
        array(
            'name'          => esc_html__( 'Sidebar', 'kucuksun' ),
            'id'            => 'sidebar-1',
            'description'   => esc_html__( 'Add widgets here.', 'kucuksun' ),
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="widget-title">',
            'after_title'   => '</h2>',
        )
    );
    // 注册商店专属侧边栏
    register_sidebar(
        array(
            'name'          => esc_html__( 'Shop', 'kucuksun' ),
            'id'            => 'shop',
            'description'   => esc_html__( 'Add widgets here.', 'kucuksun' ),
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="widget-title">',
            'after_title'   => '</h2>',
        )
    );
}
add_action( 'widgets_init', 'kucuksun_widgets_init' );

2. 选择合适的侧边栏调用方式

两种方案可实现仅商店页显示专属侧边栏,按需选择即可:

  • 方案1:修改通用sidebar.php,通过条件判断自动加载对应侧边栏
    替换原sidebar.php代码为以下内容,用WooCommerce内置的is_shop()函数判断当前页面是否为商店页:
<?php
// 商店页加载专属侧边栏
if (function_exists('is_shop') && is_shop()) {
    if (is_active_sidebar('shop')) {
        ?>
        <aside id="secondary" class="widget-area shop-widget-area">
            <?php dynamic_sidebar('shop'); ?>
        </aside>
        <?php
    }
    return;
}
// 其他页面加载默认侧边栏
if ( ! is_active_sidebar( 'sidebar-1' ) ) {
    return;
}
?>
<aside id="secondary" class="widget-area">
    <?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside>
  • 方案2:在woocommerce.php模板中单独调用
    如果不需要修改通用侧边栏逻辑,直接在woocommerce.php需要显示侧边栏的位置添加以下代码即可:
<?php
if (is_active_sidebar('shop')) {
    ?>
    <aside id="secondary" class="widget-area shop-widget-area">
        <?php dynamic_sidebar('shop'); ?>
    </aside>
    <?php
}
?>

操作完成后可以到后台小工具页面,将需要的小部件拖到「Shop」侧边栏中,打开商店页即可看到效果。

内容的提问来源于stack exchange,提问作者Ferhat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:06:02