前言
Bricks 1.5 引入了新的 bricks/element/render 筛选器。该筛选器使你能够以编程方式实现自己的条件渲染逻辑。例如:根据用户角色限制高级内容。如果此筛选器内的条件不满足(即返回 false),Bricks 不会渲染当前元素。
用法
将代码加入子主题的 functions.php:
add_filter( 'bricks/dynamic_data/render_tag', function( $tag, $post, $context ) {
// Implement a custom tag '{my_custom_tag}'
if ( $tag === 'my_custom_tag' ) {
return 'My Custom Value';
}
return $tag; // Return original tag to let other providers handle it
}, 10, 3 );
参数
$tag(string):动态数据标签字符串(不含花括号,例如 post_title:fallback)。$post(WP_Post):文章上下文。$context(string):标签被渲染所处的上下文。
示例代码
筛选返回值
add_filter( 'bricks/dynamic_data/render_tag', function( $tag, $post, $context ) {
// Implement a custom tag '{my_custom_tag}'
if ( $tag === 'my_custom_tag' ) {
return 'My Custom Value';
}
return $tag; // Return original tag to let other providers handle it
}, 10, 3 );
根据条件短路返回原值
根据条件跳过或修改返回值:
add_filter( 'bricks/dynamic_data/render_tag', function( $value, $tag ) {
if ( is_admin() ) { return $value; }
// TODO: custom logic here
return $value;
} );
补充说明
更多细节可参考 官方文档。