retesere20

wp metabox field in gutenberg

Nov 5th, 2020
25
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. if (false)
  3. {
  4.  
  5.  
  6. function myprefix_register_meta() {
  7. register_meta('vvid', '_myprefix_text_metafield', array(
  8. 'show_in_rest' => true,
  9. 'type' => 'string',
  10. 'single' => true,
  11. 'sanitize_callback' => 'sanitize_text_field',
  12. 'auth_callback' => function() {
  13. return current_user_can('edit_posts');
  14. }
  15. ));
  16. }
  17. add_action('init', 'myprefix_register_meta');
  18.  
  19. function myprefix_add_meta_box() {
  20. add_meta_box(
  21. 'myprefix_post_options_metabox',
  22. 'Post Options',
  23. 'myprefix_post_options_metabox_html',
  24. 'vvid',
  25. 'normal',
  26. 'default',
  27. array('__back_compat_meta_box' => true)
  28. );
  29. }
  30.  
  31. add_action( 'add_meta_boxes', 'myprefix_add_meta_box' );
  32.  
  33. function myprefix_post_options_metabox_html($post) {
  34. $field_value = get_post_meta($post->ID, '_myprefix_text_metafield', true);
  35. wp_nonce_field( 'myprefix_update_post_metabox', 'myprefix_update_post_nonce' );
  36. ?>
  37. <p>
  38. <label for="myprefix_text_metafield"><?php esc_html_e( 'Custom fielddddddddd', 'textdomain' ); ?></label>
  39. <br />
  40. <input class="widefat" type="text" name="myprefix_text_metafield" id="myprefix_text_metafield" value="<?php echo esc_attr( $field_value ); ?>" />
  41. </p>
  42. <?php
  43. }
  44.  
  45. function myprefix_save_post_metabox($post_id, $post) {
  46.  
  47. $edit_cap = get_post_type_object( $post->post_type )->cap->edit_post;
  48. if( !current_user_can( $edit_cap, $post_id )) {
  49. return;
  50. }
  51. if( !isset( $_POST['myprefix_update_post_nonce']) || !wp_verify_nonce( $_POST['myprefix_update_post_nonce'], 'myprefix_update_post_metabox' )) {
  52. return;
  53. }
  54.  
  55. if(array_key_exists('myprefix_text_metafield', $_POST)) {
  56. update_post_meta(
  57. $post_id,
  58. '_myprefix_text_metafield',
  59. sanitize_text_field($_POST['myprefix_text_metafield'])
  60. );
  61. }
  62. }
  63.  
  64. add_action( 'save_post', 'myprefix_save_post_metabox', 10, 2 );
  65.  
  66. function myprefix_enqueue_assets() {
  67. wp_enqueue_script(
  68. 'myprefix-gutenberg-sidebar',
  69. plugins_url( 'custom_files/gutenberg_editor_mods.js', __FILE__ ),
  70. array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data' )
  71. );
  72. }
  73. add_action( 'enqueue_block_editor_assets', 'myprefix_enqueue_assets' );
  74.  
  75. }
RAW Paste Data