-
matt_hc
Is there any way for me to conditional display a block element? For example, I am using ACF, and I have created a field group that displays if the Post Type is equal to Page. The field group has a couple of different text field (feature_header and feature_subheader). I have also created a block element called, “Page Feature Area,” and it has a hook of before_main_content. The Page Feature Area block dynamically pulls in the feature_header and feature_subheader from custom fields for each page. This is working just fine.
However, can I add another field to the ACF field group (like a True/False field with the name enable_page_feature), that allows the user to not display the Page Feature Area block on that page if enable_page_feature is set to False? I can’t quite seem to figure out how to get this to work.
-
Hi there,
This will require custom PHP coding to alter the output the block.
Can you try this?
1. add a CSS class to the parent container of the Page feature area, eg.
custom-feature-area
.
Adding CSS class(es): https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/2. Add this PHP code:
function enable_page_feature( $block_content, $block ) { if ( ! is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'custom-feature-area' ) !== false ) { $post_id = get_queried_object_id(); // More reliable in some cases $option = get_field('enable_page_feature', $post_id); if ( $option === false ) { // Strict check for false return ''; } } return $block_content; } add_filter( 'render_block', 'enable_page_feature', 10, 2 );
Adding PHP: https://docs.generatepress.com/article/adding-php/
-
matt_hc
The code worked great. That said, I am using a merged header throughout the site, as I have an image behind the header on all pages (the logo and navigation links are white). If I set the page feature to false, which hides it, I can no longer see the logo or navigation. I would like to add css to set a black background on .site-header if the page feature is not enabled. I’ve tried modifying the code to add the CSS to do this, but it doesn’t seem to be working.
function enable_page_feature( $block_content, $block ) { if ( ! is_admin() && ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'page-feature-cntr' ) !== false ) { $post_id = get_queried_object_id(); // More reliable in some cases $option = get_field('feature_area_enabled', $post_id); if ( $option === false ) { // Strict check for false // Add the CSS to the head of the page add_action('wp_head', function() { echo '<style>.site-header { background-color: black !important; }</style>'; }); return ''; } } return $block_content; } add_filter( 'render_block', 'enable_page_feature', 10, 2 );
- You must be logged in to reply to this topic.