需要从media_handle_upload
像这样:
First we get the new image ID
$attach_id = media_handle_upload( $file_handler, $_POST[\'post_id\'] );
Than we prepare the content of that alt="text"
:
// Prepare the alt="title"
$image_title = get_post( $post->ID )->post_title;
// Sanitize the title: remove hyphens, underscores & extra spaces:
$image_title = preg_replace( \'%\\s*[-_\\s]+\\s*%\', \' \', $image_title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );
And finaly we set the new image alt="text"
:
add_post_meta( $attach_id, \'_wp_attachment_image_alt\', $image_title );
上述代码失败的原因是
$post->ID
是
ID
而不是
attachment ID
(这是我们需要的)。