Post Metas in WordPress Gutenberg

Add post metas in the sidebar

    Inhaltsangabe
  1. Document Tab
    1. Example code
  2. Conclusion

I was traveling a lot today and covered almost 300 km with my car. That’s why I’ll keep my contribution very quick and short today.

Document Tab

In WordPress Gutenberg you have a panel on the right side, where you can change either the current block or the post features of the current post. I will now give you a script example of how you can create your own sections with their own properties in the “Document” area. Let’s call this section subline Subline

Example code

<?php
add_action( 'load-post.php', 'subline_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'subline_post_meta_boxes_setup' );

function subline_post_meta_boxes_setup() {
    add_action( 'add_meta_boxes', 'subline_add_post_meta_boxes' );
    add_action( 'save_post', 'subline_save_post_class_meta', 10, 2 );
}

function subline_add_post_meta_boxes() {
    add_meta_box(
        'subline-post-class',
        'Subline',
        'subline_post_class_meta_box',
        'post',
        'side',
        'default'
    );
}

function subline_post_class_meta_box( $post ) {
    wp_nonce_field( basename( __FILE__ ), 'subline_post_class_nonce' );?>

    <div class="components-base-control editor-post-excerpt__textarea">
        <div class="components-base-control__field">
            <label class="components-base-control__label" for="subline-post-class">Enter Subline here</label>
            <input type="text" name="subline-post-class" id="subline-post-class" class="edit-post-post-schedule" value="<?php echo esc_attr( get_post_meta( $post->ID, 'subline_post_class', true ) ); ?>">
        </div>
    </div>
<?php }

function subline_save_post_class_meta( $post_id, $post ) {

    if ( !isset( $_POST['subline_post_class_nonce'] ) || !wp_verify_nonce( $_POST['subline_post_class_nonce'], basename( __FILE__ ) ) )
        return $post_id;

    $post_type = get_post_type_object( $post->post_type );
    if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
        return $post_id;

    $new_meta_value = ( isset( $_POST['subline-post-class'] ) ? $_POST['subline-post-class'] : '' );
    $meta_key = 'subline_post_class';
    $meta_value = get_post_meta( $post_id, $meta_key, true );

    if ( $new_meta_value && '' == $meta_value )
        add_post_meta( $post_id, $meta_key, $new_meta_value, true );
    elseif ( $new_meta_value && $new_meta_value != $meta_value )
        update_post_meta( $post_id, $meta_key, $new_meta_value );
    elseif ( '' == $new_meta_value && $meta_value )
        delete_post_meta( $post_id, $meta_key, $meta_value );
}

Conclusion

The code is actually relatively self-explanatory. I will also program a generator over time, which will allow you to generate and save your sidebars.

Topics

Gutenberg php technology WordPress

Beitrag teilen

WhatsApp it

Folgen Sie uns