このコードの説明コメントは全部外している、ここで確認できる。
//投稿ページのアップロードとメディアライブラリへの直アップの自動変換コード
function rename_file($filename) {
global $filename_new;
$post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : '';
if( !$post_id ){
$post_id = isset( $_POST['post'] ) ? (int)$_POST['post'] : '';
}
$ext = pathinfo( $filename, PATHINFO_EXTENSION );
if( $post_id ){
$filename_new = $post_id;
return 'post-id-' . $filename_new . '.' . $ext;
} else {
$filename_new = date_i18n('ymdHi');
return 'img-' . $filename_new . '.' . $ext;
}
}
add_filter('sanitize_file_name', 'rename_file', 10);
//左サイドのアイキャッチ画像のアップロード時の自動変換コード
function auto_set_featured_image_from_content( $post_id ) {
if ( wp_is_post_revision( $post_id ) || ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) ) {
return;
}
if ( has_post_thumbnail( $post_id ) ) {
return;
}
$post = get_post( $post_id );
if ( !$post ) {
return;
}
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
if ( $output && isset( $matches[1][0] ) ) {
$image_url = $matches[1][0];
$attachment_id = attachment_url_to_postid( $image_url );
if ( $attachment_id ) {
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
add_action( 'save_post', 'auto_set_featured_image_from_content' );
