This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function attachment_link_convert($content){ | |
global $wpdb; | |
$upload_dir = wp_upload_dir(); | |
$pattern = '#(<a [^>]*href=[\'"])('.preg_quote($upload_dir['baseurl']).'/)([^\'"]*)([\'"][^>]*><img [^>]*></a>)#uism'; | |
if ( preg_match_all($pattern, $content, $matches, PREG_SET_ORDER) ) { | |
foreach ( $matches as $match ) { | |
$attachment_id = $wpdb->get_var($wpdb->prepare(" | |
select p.ID | |
from {$wpdb->posts} as p | |
inner join {$wpdb->postmeta} as m on p.ID = m.post_id | |
where m.meta_key = %s | |
and m.meta_value = %s | |
limit 1", | |
'_wp_attached_file', | |
$match[3])); | |
if ( $attachment_id ) { | |
$attachment_url = get_attachment_link($attachment_id); | |
$new_link = $match[1].$attachment_url.$match[4]; | |
$content = str_replace($match[0], $new_link, $content); | |
} | |
} | |
} | |
unset ($matches); | |
return $content; | |
} | |
add_filter('the_content','attachment_link_convert'); |
凄いやりたかったことでした!!!
素敵です。早速導入してみました。
二つだけ問題点がありました。
1.画像ファイルが日本語の場合うまくいかない?
2.画像サイズをリサイズしてアップした場合にうまくいきませんでした。
(画像ファイル名800×600.png などになった場合)
> 1.画像ファイルが日本語の場合うまくいかない?
これは、正規表現を 5 行目の $pattern の所です。これで日本語にも対応したと思います。
> 2.画像サイズをリサイズしてアップした場合にうまくいきませんでした。
これは、後で考えますね。
現状では、メディアライブラリに登録されているオリジナルのファイル名と同じリンクじゃないとメディアライブラリから検索できないので。
日本語対応ありがとうございます!うまく動きました!