wordpress - 如何为 WordPress 侧边栏创建短代码?

标签 wordpress shortcode sidebar gutenberg-blocks

我使用以下脚本向我的 WordPress 安装添加了一个自定义侧边栏,该脚本还创建了一个短代码:

// Register Sidebars
function custom_sidebars() {

    $args = array(
        'id'            => 'gutenbar',
        'class'         => 'abeng',
        'name'          => __( 'Abeng sidebar', 'text_domain' ),
        'description'   => __( 'Sidebar for block', 'text_domain' ),
    );
    register_sidebar( $args );

}
add_action( 'widgets_init', 'custom_sidebars' );
add_shortcode( 'add_sidebar', 'custom_sidebars' );

当我将 [add_sidebar] 短代码添加到古腾堡 block 时,侧边栏不会出现。但是,当我使用名为 Sidebar Shortcode [sidebar id="gutenbar"] 的插件时,侧边栏显示完美。我假设我的短代码与特定功能相关联,并且不需要选择侧边栏的名称或 ID。

我一直在想,因为侧边栏是使用一个插件添加的,该插件允许插入站点范围内可用的功能,而不是仅使用其functions.php在主题中插入,这就是短代码没有完成其工作的原因。但由于侧边栏显示在小部件区域中并允许我添加小部件,并且现在可以使用此插件,因此这显然不是问题。

在简洁编写的侧边栏简码的背后,我看不到我可能想要添加什么来使我的代码发挥作用。

我为什么要这么做?我在帖子中使用全角页面,禁用主题的默认右侧边栏(这在响应式设计中效果不佳),但仍然需要在列中重新插入侧边栏。

感谢您的帮助。

最佳答案

在 WordPress 支持论坛上的 Prashant Singh 的帮助下,我了解到创建侧边栏的函数不能用于创建将其放置在页面上的短代码。必须调用 WP native 函数 dynamic_sidebar() 创建短代码,该函数可以访问所有侧边栏 ( https://developer.wordpress.org/reference/functions/dynamic_sidebar/ )。下面是完整的脚本,其中包括清理代码,以允许在页面内正确定位。

/**
* Create sidebar and shortcode
*/
// Register Sidebars
function custom_sidebars() {

    $args = array(
        'id'            => 'gutenbar',
        'class'         => '',
        'name'          => __( 'Abeng sidebar', 'text_domain' ),
        'description'   => __( 'Sidebar for block', 'text_domain' ),
    );
    register_sidebar( $args );
}
add_action( 'widgets_init', 'custom_sidebars' );
/* Add the shortcode and allow positioning in page*/     
    add_shortcode( 'add_sidebar', 'my_custom_sidebar' );
    function my_custom_sidebar(){
        ob_start(); 
        dynamic_sidebar( 'gutenbar'); 
        $sidebar_left = ob_get_clean(); 
        $html = ' <div class="sidebar-content"> ' . $sidebar_left . ' </div> '; 
        return $html;
    }

关于wordpress - 如何为 WordPress 侧边栏创建短代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62945509/

相关文章:

html - 将元素定位到高度 : 100% div 的底部

Wordpress dynamic_sidebar 什么都不显示

php - WordPress Shortcode - 通过 ID 获取帖子数据

php - 使用自定义元查询显示带有简码的 WooCommerce 产品

wordpress - 在古腾堡的图像 block 中上传 SVG 图像

html - 需要在自定义插件的 CSS/HTML 中使图像响应

php - 允许使用 WordPress 的 Gallery Shortcode 自定义图像大小

visual-studio-code - 如何在 VS Code 侧边栏中更改字体大小?

wordpress - 使用短代码更改页面标题

html - 图像 slider 首先闪烁错误的图像