Miranda Breekweg
Miranda Breekweg

Reputation: 217

My custom add_meta_box is not showing up in wordpress admin panel

New to Wordpress and struggling with the meta boxes. Unable to get my piece of code to work/show, nor was I able find examples that work. Nothing just wants to show up in the admin panel and have no clue what I'm missing / doing wrong. Until now it looks like it's not triggering the callback function or something.

What I want to do:

Show a checkbox to hide the page's title

What I see:

No checkbox is showing up on the page edit screen

My code in functions.php:

function twentyseventeenchild_hide_title() {
    add_meta_box(
        'no-title', // Unique id
        __( 'Hide title' ), // Title
        'twentyseventeenchild_hide_title_callback', // Callback
        'post', // Screen (such as post type, link or comment)
        'normal', // Context (normal, advanced, side)
        'default' // Priority (default, core, high, low)
        // Callback arguments
    );
}
add_action( 'add_meta_boxes', 'twentyseventeenchild_hide_title' );

/**
 * Meta box display callback.
 *
 * @param WP_Post $post Current post object.
 */
function twentyseventeenchild_hide_title_callback( $post ) {
    $meta = get_post_meta($post->ID, '_title', true);
    ?>
    <label><?php __('Hide title') ?></label>
    <input id="no_title" type="checkbox" autocomplete="off" value="<?=esc_attr($meta)?>" name="page_title">
    <?php
}

Upvotes: 1

Views: 1383

Answers (1)

You're using checkbox incorrectly.

See input checkbox: https://www.w3schools.com/tags/att_input_type_checkbox.asp Your method need to be like:

    function twentyseventeenchild_hide_title_callback( $post ) {
        $meta = get_post_meta($post->ID, '_title', true);
        ?>
            <input id="no_title" type="checkbox" <?php ($meta === '1' ? 'selected' : ''); ?> name="page_title">
            <label for="no_title"><?php _e('Hide title') ?></label>
        <?php
    }

_e() is for translate and echo, __() only return string and not print it. ($meta === '1' ? 'selected' : ''); is because when you save metabox value truewill be saved as string 1. With this ternary you can show as selected this metabox if value is euqals 1 (as string).

Upvotes: 3

Related Questions