条件显示

容器在显示选项方面非常灵活。 默认情况下,容器会显示在所有相关实体上(帖子元容器的所有帖子类型、术语元容器的所有术语等),但是,您可以将容器可见性限制为特定的帖子类型、分类术语、层次结构级别等,并且具有无限的复杂性 .

使用以下方法之一向容器添加显示条件:

->where( $condition, $comparison_operator, $value ) - 添加一个与其他条件有 AND 关系的条件

->or_where( $condition, $comparison_operator, $value ) - 添加一个与其他条件有 OR 关系的条件

注意:链接条件的行为与具有多个条件的普通 php if 语句完全相同。

Parameter Description
$condition A condition type name as a string (refer to the Condition Types page)
$comparison_operator Can be one of the following: '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN', 'CUSTOM'
$value The value to check against. IN and NOT IN operators expect an array; CUSTOM operator expects a callable
注意:您可以使用匿名函数作为所有比较运算符的 $value 参数,以便延迟加载值,这在评估值是一项资源密集型任务时非常有用。

CUSTOM 比较运算符

此运算符允许您提供一个可调用对象,无论此条件是否满足,它都必须返回一个布尔值。 这样,如果内置功能不适合您的需求,您可以更好地控制值的比较方式。

例如,如果您希望容器仅显示在层次结构中偶数级别的页面上,您的代码将如下所示:

Container::make( 'post_meta', 'Custom Data' )
    ->where( 'post_type', '=', 'page' )
    ->where( 'post_level', 'CUSTOM', function( $post_level ) {
        return ( $post_level % 2 === 0 );
    } );

例子

在所有页面上显示 Post Meta Container

Container::make( 'post_meta', 'Custom Data' )
    ->where( 'post_type', '=', 'page' )
    ->add_fields( array( ... ) );

在静态主页上显示 Post Meta Container

Container::make( 'post_meta', 'Custom Data' )
    ->where( 'post_id', '=', get_option( 'page_on_front' ) )
    ->add_fields( array( ... ) );

仅当当前用户是管理员或编辑时才显示 User Meta Container

Container::make( 'post_meta', 'Custom Data' )
    ->where( 'current_user_role', 'IN', array( 'administrator', 'editor' ) )
    ->add_fields( array( ... ) );

嵌套逻辑

为了实现嵌套显示逻辑, where() or_where() 方法还支持使用可调用对象调用:

Container::make( 'post_meta', 'Custom Data' )
    ->where( function( $lvl1_condition ) {
        $lvl1_condition->where( $condition, $comparison_operator, $value );
        $lvl1_condition->where( function( $lvl2_condition ) {
            ... // can be nested infinitely
        } );
        ...
    } );

例如,如果当前用户是administrator,则容器在所有帖子类型上可见,或者如果当前用户是editor ,则仅在page帖子类型上可见,您的代码将如下所示:

Container::make( 'post_meta', 'Custom Data' )
    ->where( 'current_user_role', '=', 'administrator' )
    ->or_where( function( $condition ) {
        $condition->where( 'current_user_role', '=', 'editor' );
        $condition->where( 'post_type', '=', 'page' );
    } );