$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Hide or show Gutenberg custom block using date range|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Hide or show Gutenberg custom block using date range

matteradmin6PV0评论

I have created a custom block with a dateFrom and dateTo attribute (which work), but would like to hide the block on the front end between these dates.

Not sure if this is even possible?

I don't just want to add a class and hide with css, as i don't want the block to be visible, even in the code. Any advise or pointing me in right direction would be appreciated.

import classnames from 'classnames'
import ResizableBox from 're-resizable'

const { isFinite, find, omit } = window.lodash;
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { 
    PanelBody, 
    DateTimePicker,
} = wpponents;
const { __experimentalGetSettings  } = wp.date;
const { Fragment } = wp.element;
const { compose,withState } = wppose;
const {
    InspectorControls,
    InnerBlocks,
} = wp.editor;

registerBlockType( 'block/timed-block', {
    title: __( 'Timed block' ), // Block title.
    icon: 'align-center', // Block icon from Dashicons → /.
    category: 'layout', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
    keywords: [
        __( 'section' ),
        __( 'container' ),
    ],
    attributes: {
        dateFrom: {
            type: 'strings',
        },
        dateTo: {
            type: 'string',
        },
    },
    edit: function( {  attributes, setAttributes,className }) {

        const settings = __experimentalGetSettings();
        const is12HourTime = /a(?!\\)/i.test(
            settings.formats.time
                .toLowerCase() // Test only the lower case a
                .replace( /\\\\/g, '' ) // Replace "//" with empty strings
                .split( '' ).reverse().join( '' ) // Reverse the string and test for "a" not followed by a slash
        );

        const { 
            dateFrom,
            dateTo
        } = attributes;

        return (
            <Fragment>
                <InspectorControls>
                    <PanelBody
                        title={ __( 'Date from' ) }
                        initialOpen={ false }
                    >
                     <DateTimePicker
                            currentDate={ dateFrom }
                            onChange={ ( date ) => {
                                setAttributes( {
                                    dateFrom: date,
                                } );
                            } }
                            locale={ settings.l10n.locale }
                            is12Hour={ is12HourTime }
                        />
                    </PanelBody>
                    <PanelBody
                        title={ __( 'Date to' ) }
                        initialOpen={ false }
                    >
                    <DateTimePicker
                            currentDate={ dateTo }
                            onChange={ ( date ) => {
                                setAttributes( {
                                    dateTo: date,
                                } );
                            } }
                            locale={ settings.l10n.locale }
                            is12Hour={ is12HourTime }
                        />

                    </PanelBody>

                </InspectorControls>
                <section
                className={ className }
                >   
                    <InnerBlocks />
                </section>
            </Fragment>
        );
    },

    save: function( { attributes, className }) {
        const { 
            dateFrom,
            dateTo
        } = attributes;

            return (
                <section className={className}>
                <InnerBlocks.Content />
                </section>
            );


    },

    /**
     * wrapper props
     * @param {*} attributes 
     */
    getEditWrapperProps( attributes ) {
        return { 'data-align': 'wide' };
    },
} );

UPDATE

I have tried to add and remove filter as below, but i can't seem to get the BlockName to output

remove_filter( 'the_content', 'do_blocks', 7 );

add_filter( 'the_content', function( $content ) {


    $blocks = gutenberg_parse_blocks( $content );
    $output = '';

    foreach ( $blocks as $block ) {


         if ( 'block/timed-block' === $block['blockName'] ) {
             $output .= '';
         } else {
            $output .= gutenberg_render_block( $block );
         }

    }
    return $output;

}, 10, 2 );

I have created a custom block with a dateFrom and dateTo attribute (which work), but would like to hide the block on the front end between these dates.

Not sure if this is even possible?

I don't just want to add a class and hide with css, as i don't want the block to be visible, even in the code. Any advise or pointing me in right direction would be appreciated.

import classnames from 'classnames'
import ResizableBox from 're-resizable'

const { isFinite, find, omit } = window.lodash;
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { 
    PanelBody, 
    DateTimePicker,
} = wpponents;
const { __experimentalGetSettings  } = wp.date;
const { Fragment } = wp.element;
const { compose,withState } = wppose;
const {
    InspectorControls,
    InnerBlocks,
} = wp.editor;

registerBlockType( 'block/timed-block', {
    title: __( 'Timed block' ), // Block title.
    icon: 'align-center', // Block icon from Dashicons → https://developer.wordpress/resource/dashicons/.
    category: 'layout', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
    keywords: [
        __( 'section' ),
        __( 'container' ),
    ],
    attributes: {
        dateFrom: {
            type: 'strings',
        },
        dateTo: {
            type: 'string',
        },
    },
    edit: function( {  attributes, setAttributes,className }) {

        const settings = __experimentalGetSettings();
        const is12HourTime = /a(?!\\)/i.test(
            settings.formats.time
                .toLowerCase() // Test only the lower case a
                .replace( /\\\\/g, '' ) // Replace "//" with empty strings
                .split( '' ).reverse().join( '' ) // Reverse the string and test for "a" not followed by a slash
        );

        const { 
            dateFrom,
            dateTo
        } = attributes;

        return (
            <Fragment>
                <InspectorControls>
                    <PanelBody
                        title={ __( 'Date from' ) }
                        initialOpen={ false }
                    >
                     <DateTimePicker
                            currentDate={ dateFrom }
                            onChange={ ( date ) => {
                                setAttributes( {
                                    dateFrom: date,
                                } );
                            } }
                            locale={ settings.l10n.locale }
                            is12Hour={ is12HourTime }
                        />
                    </PanelBody>
                    <PanelBody
                        title={ __( 'Date to' ) }
                        initialOpen={ false }
                    >
                    <DateTimePicker
                            currentDate={ dateTo }
                            onChange={ ( date ) => {
                                setAttributes( {
                                    dateTo: date,
                                } );
                            } }
                            locale={ settings.l10n.locale }
                            is12Hour={ is12HourTime }
                        />

                    </PanelBody>

                </InspectorControls>
                <section
                className={ className }
                >   
                    <InnerBlocks />
                </section>
            </Fragment>
        );
    },

    save: function( { attributes, className }) {
        const { 
            dateFrom,
            dateTo
        } = attributes;

            return (
                <section className={className}>
                <InnerBlocks.Content />
                </section>
            );


    },

    /**
     * wrapper props
     * @param {*} attributes 
     */
    getEditWrapperProps( attributes ) {
        return { 'data-align': 'wide' };
    },
} );

UPDATE

I have tried to add and remove filter as below, but i can't seem to get the BlockName to output

remove_filter( 'the_content', 'do_blocks', 7 );

add_filter( 'the_content', function( $content ) {


    $blocks = gutenberg_parse_blocks( $content );
    $output = '';

    foreach ( $blocks as $block ) {


         if ( 'block/timed-block' === $block['blockName'] ) {
             $output .= '';
         } else {
            $output .= gutenberg_render_block( $block );
         }

    }
    return $output;

}, 10, 2 );
Share Improve this question edited Nov 15, 2018 at 12:31 DesignMonkeyJim asked Nov 14, 2018 at 20:10 DesignMonkeyJimDesignMonkeyJim 3493 silver badges9 bronze badges 2
  • I guess you mean looking into do_block filter, that might have been renamed render_block. Match the corresponding block, peek into the date attributes and remove the block from the rendered content if it matches the correct condition? – birgire Commented Nov 14, 2018 at 21:17
  • @birgire Yes, this is what i want my block to do. Where/how would i do this? – DesignMonkeyJim Commented Nov 14, 2018 at 21:28
Add a comment  | 

1 Answer 1

Reset to default 7

Here's an untested suggestion, to remove an HTML block of type:

<!-- wp:block/timed-block {"dateFrom":"2018-11-14", "dateTo":"2018-12-18"} -->
    <section>
       ...
    </section>
<!-- /wp:block/timed-block -->

from the rendered content, using the render_block filter (available in 5.0+):

add_filter( 'render_block', function( $block_content, $block ) {
    // Remove the block/timed-block from the rendered content.
    if ( 'block/timed-block' === $block['blockName'] ) {
        $block_content = '';
    }
    return $block_content;
}, 10, 2 );

One could further handle date constrains with the parsed attributes $block['attr']['dateFrom'] and $block['attr']['dateTo'] as needed.

Hope it helps!

Post a comment

comment list (0)

  1. No comments so far