Skip to content

Instantly share code, notes, and snippets.

@kalamun
Last active September 2, 2019 08:05
Show Gist options
  • Save kalamun/a5ea0168f5ff781aca681a4aea7426b4 to your computer and use it in GitHub Desktop.
Save kalamun/a5ea0168f5ff781aca681a4aea7426b4 to your computer and use it in GitHub Desktop.
/*
* WORDPRESS: add a text field inside the post-thumbnail box in Gutenberg
*/
"use strict"
const el = wp.element.createElement;
const withState = wp.compose.withState;
const withSelect = wp.data.withSelect;
const withDispatch = wp.data.withDispatch;
wp.hooks.addFilter(
'editor.PostFeaturedImage',
'kalamun',
wrapPostFeaturedImage
);
function wrapPostFeaturedImage( OriginalComponent ) {
return function( props ) {
return (
el(
wp.element.Fragment,
{},
el(
OriginalComponent,
props
),
el(
composedTextInput
)
)
);
}
}
class KalamunVideoAlternative extends React.Component {
render() {
const {
meta,
update_video_url,
} = this.props;
return (
el(
wp.components.TextControl,
{
label: "URL video",
help: "Se specificato, nella pagina mostra un video al posto dell'immagine",
value: meta._video_url,
onChange:
( value ) => {
this.setState( { _video_url: value } );
update_video_url( value, meta );
}
}
)
)
}
}
const composedTextInput = wp.compose.compose( [
withState( ( value ) => { _video_url: value } ),
withSelect( ( select ) => {
const currentMeta = select( 'core/editor' ).getCurrentPostAttribute( 'meta' );
const editedMeta = select( 'core/editor' ).getEditedPostAttribute( 'meta' );
return {
meta: { ...currentMeta, ...editedMeta },
};
} ),
withDispatch( ( dispatch ) => ( {
update_video_url( value, meta ) {
meta = {
...meta,
_video_url: value,
};
dispatch( 'core/editor' ).editPost( { meta } );
},
} ) ),
] )( KalamunVideoAlternative );
/*
* Then add this to functions.php in order to save the field value
add_action( 'init', 'kalamun_post_thumbnail_register_meta' );
function kalamun_post_thumbnail_register_meta()
{
register_meta( 'post', '_video_url', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function() {
return current_user_can( 'edit_posts' );
}
] );
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment