-
-
Save ksuzushima/8a3ada85657ba6bb7b7bd0833e129d3f to your computer and use it in GitHub Desktop.
WordPressで画像のURLからアタッチメントIDを取得する
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 | |
/** | |
* 画像のURLのサイズ違いのURLを取得する | |
* | |
* @param string $url 画像のURL | |
* @param string $size 画像のサイズ (thumbnail, medium, large or full) | |
*/ | |
function get_attachment_image_src($url, $size) { | |
$image = wp_get_attachment_image_src(get_attachment_id($url), $size); | |
return $image[0]; | |
} | |
/** | |
* 画像のURLからattachemnt_idを取得する | |
* | |
* @param string $url 画像のURL | |
* @return int attachment_id | |
*/ | |
function get_attachment_id($url) | |
{ | |
global $wpdb; | |
$sql = "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s"; | |
preg_match('/([^\/]+?)(-e\d+)?(-\d+x\d+)?(\.\w+)?$/', $url, $matches); | |
$post_name = $matches[1]; | |
return (int)$wpdb->get_var($wpdb->prepare($sql, $post_name)); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment