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.
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.
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');
}
}