Created
December 29, 2022 14:42
-
-
Save vincentorback/105a9da66b1e4a63879286ab1c3da242 to your computer and use it in GitHub Desktop.
Add setting to wordpress gutenberg block to hide if after
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ThemeNamespace = 'my-theme' | |
wp.hooks.addFilter('blocks.registerBlockType', ThemeNamespace, function (settings) { | |
if (settings.name === 'core/paragraph') { | |
settings.attributes = Object.assign(settings.attributes, { | |
expirationDate: { | |
type: 'string', | |
default: null, | |
}, | |
}) | |
} | |
}) | |
const expirationControl = wp.compose.createHigherOrderComponent((BlockEdit) => { | |
return (props) => { | |
const { attributes, setAttributes, isSelected } = props | |
const [toggle, setToggle] = wp.element.useState( | |
Boolean(attributes?.expirationDate?.length) | |
) | |
return ( | |
<wp.element.Fragment> | |
<BlockEdit {...props} /> | |
{isSelected && ( | |
<wp.blockEditor.InspectorAdvancedControls> | |
<wp.components.BaseControl | |
label={wp.i18n.__('Hide block after date', ThemeNamespace)} | |
> | |
<wp.components.ToggleControl | |
checked={toggle} | |
onChange={(value) => { | |
setToggle((prev) => !prev) | |
if (value === false) { | |
setAttributes({ | |
expirationDate: null, | |
}) | |
} | |
}} | |
/> | |
{toggle && ( | |
<wp.components.DatePicker | |
currentDate={attributes.expirationDate} | |
onChange={(value) => { | |
setAttributes({ expirationDate: value }) | |
}} | |
startOfWeek={1} | |
/> | |
)} | |
</wp.components.BaseControl> | |
</wp.blockEditor.InspectorAdvancedControls> | |
)} | |
</wp.element.Fragment> | |
) | |
} | |
}, 'expirationControl') | |
wp.hooks.addFilter( | |
'editor.BlockEdit', | |
'teg/expiration-control', | |
expirationControl | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Conditional block rendering if have expirationDate attribute | |
*/ | |
add_filter('render_block', function ($block_content, $block) { | |
if (isset($block['attrs']['expirationDate'])) { | |
$expirationDate = $block['attrs']['expirationDate']; | |
$expirationDateTime = strtotime($expirationDate); | |
$nowTime = strtotime('now'); | |
if ($nowTime > $expirationDateTime) { | |
return ''; | |
} | |
} | |
return $block_content; | |
}, 10, 2); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment