1

Hello im creating my custom checkbox in gallery and i already add that , but save doesn't work , can someone take a look and tell me where should i put meta keys ?

function wporg_add_custom_box()
{
$screens = ['attachment'];
foreach ($screens as $screen) {
    add_meta_box(
        'wporg_box_id',           // Unique ID
        'Custom Meta Box Title',  // Box title
        'wporg_custom_box_html',  // Content callback, must be of type callable
        $screen                   // Post type
    );
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box');


function wporg_custom_box_html($post)
{
$value = get_post_meta($post->ID, '_wporg_meta_key', true);
 ?>
<input type="checkbox" name="include_in_image_gallery" <?php selected($value, $post->ID); ?> >
 <?php
}

 function wporg_save_postdata($post_id)
{
 if (array_key_exists('wporg_field', $_POST)) {
    update_post_meta(
        $post_id,
        '_wporg_meta_key',
        $_POST['include_in_image_gallery']
    );
}
}
add_action('save_post', 'wporg_save_postdata');

My meta key name is: include_in_image_gallery

I want to use that meta in wp_query in another subpage.

Any idea? Thanks and best regards.

  • Is there any reason why the names of keys, fields, variables and functions have no meaning at all? ;) – Krzysiek Dróżdż Jan 8 at 23:20
  • Yes , its from tutorial but with select , options. i will change that after all ; p – Mariusz Jan 8 at 23:25
  • It would be a lot easier to understand that code and help you, if the names were meaningful ;) – Krzysiek Dróżdż Jan 8 at 23:30
0

First of all you have an if statement that is always false in your save function.

I don’t see any input called wporg_field anywhere in your meta box, so most probably there is no such field - so that condition is false and no meta field is saved.

Another problem is that you make wrong assumptions on how checkboxes work. If checkbox is not checked, then it won’t be sent in POST array.

Here’s a fixed version - it should work:

function wporg_save_postdata($post_id)
{
    if ( array_key_exists('include_in_image_gallery', $_POST) ) {
        update_post_meta(
            $post_id,
            '_wporg_meta_key',
            $_POST['include_in_image_gallery']
        );
    } else {
        delete_post_meta($post_id, '_wporg_meta_key');
    }
}
  • Thanks for your answer ! anyway problem is not fixed , i think its maybe because of "<?php selected($value, $post->ID); ?> >" it propably should be checked() ? – Mariusz Jan 8 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.