在我的网站上,我有一个前端表单,供用户创建帖子和上传图像。它工作得很好,但我似乎不知道如何限制每篇文章的图片数量。
图像附件会保存到自定义字段,那么有没有办法限制自定义字段允许的值的数量?
我也遇到过this post 但无法让它工作。
用于上载文件的当前代码--
// THE PHOTO UPLOAD HERE
if(isset($_POST["savepics2"])) {
$attachments = get_children( array( \'post_parent\' => $v_Id ) );
$count = count( $attachments );
if ($count == 25) {
echo \'limit reached\';
} else {
if (!empty($_FILES[\'vidPix\'][\'tmp_name\'][0])) {
$i = 1;
$files = $_FILES[\'vidPix\'];
foreach ($files[\'name\'] as $key => $value) {
if ($files[\'name\'][$key]) {
$file = array(
\'name\' => $files[\'name\'][$key],
\'type\' => $files[\'type\'][$key],
\'tmp_name\' => $files[\'tmp_name\'][$key],
\'error\' => $files[\'error\'][$key],
\'size\' => $files[\'size\'][$key]
);
$_FILES = array("sight" . $i => $file);
add_filter( \'upload_dir\', \'wpse_141088_upload_dir\' );
add_filter(\'intermediate_image_sizes_advanced\', \'no_image_resizing\');
$mfile = wp_handle_upload($files, $upload_overrides );
$newvidPix = sight("sight" . $i, $v_Id);
remove_filter( \'upload_dir\', \'wpse_141088_upload_dir\' );
remove_filter(\'intermediate_image_sizes_advanced\', \'no_image_resizing\');
// Convert the image to PNG and delete the old image.
attachment_to_png( $newvidPix );
if ($i == 1) {
update_post_meta($v_Id, \'_thumbnail_id\', $newvidPix);
}
add_post_meta($v_Id, \'vid_pix\', $newvidPix, false);
}
$i++;
}
}
}
}
有什么想法吗?谢谢
最合适的回答,由SO网友:Sally CJ 整理而成
你可以这样做—请参阅// {comment}
:
if (isset($_POST["savepics2"])) {
// Set max number of files allowed.
$max_files = 25;
$attachments = get_children( array( \'post_parent\' => $v_Id ) );
$count = count( $attachments );
// Check if limit already reached.
if ($count >= $max_files) {
echo \'limit reached\';
// If not, then upload the files.
} else {
if (!empty($_FILES[\'vidPix\'][\'tmp_name\'][0])) {
$i = 1;
$files = $_FILES[\'vidPix\'];
foreach ($files[\'name\'] as $key => $value) {
// Check if limit already reached.
if ( $count >= $max_files ) {
echo \'limit reached\';
break;
}
// If not, then upload next file.
if ($files[\'name\'][$key]) {
...your code here...
}
$i++;
$count++; // increment the count
}
}
}
}