Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Created December 29, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincentorback/105a9da66b1e4a63879286ab1c3da242 to your computer and use it in GitHub Desktop.
Save vincentorback/105a9da66b1e4a63879286ab1c3da242 to your computer and use it in GitHub Desktop.
Add setting to wordpress gutenberg block to hide if after
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
)
<?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