提交表单后,请保持选中复选框。自定义帖子类型,WordPress

时间:2018-10-16 14:34:07

标签: php html wordpress wordpress-theming

我正在制作自己的自定义帖子类型,其中当前正在显示图库中的所有图像,并为每个图像提供一个复选框。我希望用户能够选中他/她想要在帖子上显示的图像的复选框。这部分有效。问题是提交表单后,该复选框未选中。如何保持检查状态?

function po_product_image_html($post) {

echo '<div style="width: 80px; display: inline-block;">';

    $imgs = get_media_library_images();

    foreach ($imgs as $img)
    {
        echo '<img style="height: 80px; width: 80px; padding: 10px;" src="'.$img.'" />';
        echo '<input name="product_image[]" type="checkbox" value="'.$img.'" />';
    }           

echo '</div>';

}

用于保存表格的功能。

function po_products_save_postdata() {

global $post;

update_post_meta($post->ID, 'product_desc', $_POST['product_desc']);
update_post_meta($post->ID, 'product_url', $_POST['product_url']);
update_post_meta($post->ID, 'product_image', $_POST['product_image']);

}

add_action('save_post', 'po_products_save_postdata');

用于从第一个代码段中使用的媒体库获取图像的功能。

function get_media_library_images()
{
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_status' => 'inherit',
    'posts_per_page' => -1
);

$query_images = new WP_Query($args);

$images = array();

foreach ($query_images->posts as $image)
{
    $images[] = $image->guid;
}

return $images;
}

我在复选框中尝试了isset($_POST['product_image'])echo checked="checked"的问题,但到目前为止还没有运气。问题$_POST['product_image']是数组吗?

最诚挚的问候,Mac。

1 个答案:

答案 0 :(得分:0)

设法解决此问题:

echo '<div>';

global $post;

$imgs = get_media_library_images();
$post_selected_images = get_post_meta($post->ID, 'product_image', true);

foreach ($imgs as $img) {
    <input name="product_image[]" type="checkbox" <?php if(in_array($img, $post_selected_images)) echo 'checked="checked"'; ?> value="<?php echo $img ?>" />
    <?php
    echo '</div>';
}           

echo '</div>';

如果$ img变量的值存储在$ post_selected_images数组中,我只需在输入元素中回显'checked =“ checked”'。

相关问题