-
aaronmckeon
Is it possible to have a condition return true if a post is of a particular post type? I do not see an option for “post type” in the drop-down, and I cannot use location because I want the conditional blocks to be inside of archive loops. Thanks for any help.
— Aaron
-
George
There isn’t a built-in post type condition, but you can add one with a custom condition class.
Here are the docs for reference.Add the following to a code snippets plugin or your child theme’s
functions.php:add_action( 'generateblocks_register_conditions', function() { class Custom_Post_Type_Condition extends GenerateBlocks_Pro_Condition_Abstract { public function evaluate( $rule, $operator, $value, $context = [] ) { $post_id = ! empty( $context['post_id'] ) ? $context['post_id'] : get_the_ID(); $current_type = get_post_type( $post_id ); if ( 'is' === $operator ) { return $current_type === $rule; } if ( 'is_not' === $operator ) { return $current_type !== $rule; } return false; } public function get_rules() { $post_types = get_post_types( [ 'public' => true ], 'objects' ); $rules = []; foreach ( $post_types as $post_type ) { $rules[ $post_type->name ] = $post_type->label; } return $rules; } public function get_rule_metadata( $rule ) { return [ 'needs_value' => false, 'value_type' => 'none', 'supports_multi' => false, ]; } public function sanitize_value( $value, $rule ) { return sanitize_text_field( $value ); } } GenerateBlocks_Pro_Conditions_Registry::register( 'post_type', [ 'label' => __( 'Post Type', 'flavor' ), 'operators' => [ 'is', 'is_not' ], 'priority' => 50, ], 'Custom_Post_Type_Condition' ); } );Once added, you’ll see a Post Type option in the conditions dropdown. Select it, then choose the specific post type from the rules dropdown (e.g. Posts, Pages, Products, etc.) and set the operator to is or is not.
This respects the loop context, so it will correctly evaluate the post type of each item inside a Query Loop on your archive pages.
-
aaronmckeon
Great – that worked. Thanks.
-
George
No problem!
- You must be logged in to reply to this topic.