wordpress - 使用 Wordpress 简码函数呈现 Gutenberg 块,将属性作为参数发送
问题描述
给定画廊 ID,我有一个生成画廊的简码。
function rb_scroll_gallery_shortcode( $atts, $content ) {
$a = shortcode_atts( array(
'id' => -1,
), $atts );
$gallery_ID = $a['id'];
$output = '';
if($gallery_ID != -1){
ob_start();
$gallery = new RB_Scroll_Gallery($gallery_ID);
$gallery->render();
$output = ob_get_clean();
}
return $output;
}
add_shortcode( 'rb_scroll_gallery', 'rb_scroll_gallery_shortcode' );
现在,我制作了一个在编辑器中完美运行的 Gutenberg 块。您可以选择一个画廊,它将保存。但是,我不想重复代码并将 html 放在 save 属性和 php 代码中。
所以我想知道是否有一种方法可以使用相同rb_scroll_gallery_shortcode
的函数在前端渲染块。
我已经看到您可以使用register_block_type
并将其设置render_callback
为rb_scroll_gallery_shortcode
,但我需要在块中选择的 ID 将其发送到$atts
数组中的函数
//This uses the shortcode funtion, but doesn't gives the gallery ID
register_block_type( 'cgb/block-rb-scroll-gallery-block', array(
'render_callback' => 'rb_scroll_gallery_shortcode',
) );
解决方案
您可以尝试将简码转换为古腾堡块并在您的主题中使用后,
在 PHP 中注册动态块回调
/**
* Register the GitHub Gist shortcode
*/
function gggb_init() {
add_shortcode( 'github-gist', 'gggb_render_shortcode' );
register_block_type( 'github-gist-gutenberg-block/github-gist', array(
'render_callback' => 'gggb_render_shortcode',
) );
}
add_action( 'init', 'gggb_init' );
When your block is rendered on the frontend, it will be processed by your render callback:
function gggb_render_shortcode( $atts ) {
if ( empty( $atts['url'] )
|| 'gist.github.com' !== parse_url( $atts['url'], PHP_URL_HOST ) ) {
return '';
}
return sprintf(
'<script src="%s"></script>',
esc_url( rtrim( $atts['url'], '/' ) . '.js' )
);
}
**Note:** this render callback is intentionally different than the Gutenberg block’s edit callback. Our preference is to use GitHub’s provided JavaScript embed code because this lets GitHub change the embed’s behavior at a future date without requiring a developer to make changes.
请参阅链接以获取更多信息,https://pantheon.io/blog/how-convert-shortcode-gutenberg-block
推荐阅读
- mysql - Mysql Query:找到图书馆上结账次数最多的人?
- java - 构建后某些设备上的网络错误
- oracle - Teradata 到 Oracle Query eaxdata 转换
- javascript - 响应式全宽 Wordpress 帖子图片
- java - java中.push()的等效函数?
- java - 为 java jersey 应用程序创建 docker 容器
- xamarin - 在 Xamarin 表单中打开另一个内容页面
- installation - 如何使用 Inno Setup 查找 HKLM 子文件夹的名称?
- java - 循环遍历多个数组 - 电话号码到单词生成器
- javascript - Ajax 请求有多少开销