我正在使用此表单替换前端表单上的特色图像和帖子标题:
<form id="featured_upload" name="featured_upload" method="post" action="#" enctype="multipart/form-data">
<p><label for="title">Title</label><input type="text" id="title" value="<?php echo $post_to_edit->post_title; ?>" size="45" name="title" /></p>
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" required />
<p><input type="hidden" name="post_id" id="post_id" value="" /></p>
<?php wp_nonce_field( \'my_image_upload\', \'my_image_upload_nonce\' ); ?>
<input id="" name="" type="submit" value="Upload"/>
</form>
Here\'s the saving process
// Check the nonce is valid, and the user can edit this post.
if ( isset( $_POST[\'my_image_upload_nonce\'], $_POST[\'post_id\'] )
&& wp_verify_nonce( $_POST[\'my_image_upload_nonce\'], \'my_image_upload\' )
&& current_user_can( \'manage_options\', $_POST[\'post_id\'] )) {
include(\'wp-admin/includes/image.php\' );
include(\'wp-admin/includes/file.php\' );
include(\'wp-admin/includes/media.php\' );
// Let WordPress handle the upload.
$attachmentID = get_post_thumbnail_id();
$attachment_path = get_attached_file( $attachmentID);
//Delete attachment from database only, not file
$delete_attachment = wp_delete_attachment($attachmentID, true);
//Delete attachment file from disk
$delete_file = unlink($attachment_path);
//Form attachment Field name.
$file_handler = \'my_image_upload\';
$attach_id = media_handle_upload( $file_handler, $_POST[\'post_id\'] );
//changing the post title
if(!empty($_POST[\'title\'])) {
//$new_title = sanitize_title($_POST[\'title\']);
$new_slug = sanitize_title($_POST[\'title\']);
$my_post = array(\'post_title\' => $_POST[\'title\'],\'post_name\' => $new_slug);
// Update new post title into the database
wp_update_post( $my_post );
The problem:
我需要上传的图片与新的帖子标题一起保存(
$_POST[\'title\']
)
Example:
所选图像为
image1.jpg
新职位名称为renamed post
(就像在$_POST[\'title\']
)
在上载过程中,image1.jpg
应重命名为renamed-post.jpg
最合适的回答,由SO网友:Chetan Vaghela 整理而成
您可以使用sanitize_file_name
筛选以重命名文件。将此代码放入活动主题的函数中。php,如果仅获取title
要求我已经测试了这段代码,它工作得很好。职位名称:https://prnt.sc/q3thzw已上载重命名的图像:https://prnt.sc/q3tib7
function make_filename_as_post_name($filename) {
$info = pathinfo($filename);
$ext = empty($info[\'extension\']) ? \'\' : \'.\' . $info[\'extension\'];
$name = basename($filename, $ext);
$new_name = $_REQUEST[\'title\'];
if(!empty($new_name)){
# Replace space with dash
$new_name = preg_replace(\'/\\s+/\', \'-\', $new_name);
return $new_name . $ext;
}else{
return $name . $ext;
}
}
add_filter(\'sanitize_file_name\', \'make_filename_as_post_name\', 10);
如果这对你有用,请告诉我!