WordPress에서 파일 경로별로 첨부 파일 ID 가져오기
파일 경로를 알고 첨부 아이디를 받고 싶습니다.
URL을 취득하기 위해서는 ID가 필요하지만 역방향(URL이 아닌 경로)이 필요합니다.
업데이트: wp 4.0.0 이후 이 작업을 수행할 수 있는 새로운 기능이 있습니다.아직 테스트하지 않았지만, 다음과 같습니다.
https://developer.wordpress.org/reference/functions/attachment_url_to_postid/
오래된 답변: 지금까지 제가 찾은 최고의 솔루션은 다음과 같습니다.
https://frankiejarrett.com/2013/05/get-an-attachment-id-by-url-in-wordpress/
두 가지 이유로 가장 좋다고 생각합니다.
- 일부 무결성 검사를 수행합니다.
- 도메인에 구애받지 않습니다.이렇게 하면 사이트가 안전하게 이동할 수 있습니다.이것은 저에게 있어서 중요한 기능입니다.
저는 pippinsplugins.com에서 찍은 이 멋진 사진을 사용했습니다.
기능에 이 기능을 추가합니다.php 파일
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
그런 다음 페이지 또는 템플릿에서 다음 코드를 사용하여 ID를 저장/인쇄/사용합니다.
// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';
// store the image ID in a var
$image_id = pippin_get_image_id($image_url);
// print the id
echo $image_id;
최초 투고 : https://pippinsplugins.com/retrieve-attachment-id-from-image-url/
Hope ti help;) 프란체스코
해라attachment_url_to_postid
기능.
$rm_image_id = attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
echo $rm_image_id;
파일 경로에 대해 제대로 또는 안정적으로 작동하는 다른 답변은 없습니다.Pippin의 기능을 사용한 답변도 결함이 있어 "WordPress Way"를 실제로 실행하지 않습니다.
이 함수는 경로 또는 URL 중 하나를 지원하며, 마지막 처리를 올바르게 수행하기 위해 내장된 WordPress 함수 attachment_url_to_postid에 의존합니다.
/**
* Find the post ID for a file PATH or URL
*
* @param string $path
*
* @return int
*/
function find_post_id_from_path( $path ) {
// detect if is a media resize, and strip resize portion of file name
if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
$path = str_ireplace( $matches[1], '', $path );
}
// process and include the year / month folders so WP function below finds properly
if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
unset( $matches[0] );
$path = implode( '', $matches );
}
// at this point, $path contains the year/month/file name (without resize info)
// call WP native function to find post ID properly
return attachment_url_to_postid( $path );
}
잘라낸 URL
이전 답변 중 자른 내용이 포함된 첨부 파일 URL에 대한 ID 검색을 지원하지 않았습니다.
예:/uploads/2018/02/my-image-300x250.jpg
v.s./uploads/2018/02/my-image.jpg
솔루션
WP Scholar의 Mika가 블로그에 글을 써서 이 Gist에 코드를 올렸어요.원래 URL 룩업과 잘라낸 URL 룩업을 모두 처리합니다.
아래의 코드를 참고용으로 기재했습니다만, 도움이 될 것 같으면, 코멘트를 남기거나 요지의 스타를 붙이는 것을 추천합니다.
/**
* Get an attachment ID given a URL.
*
* @param string $url
*
* @return int Attachment ID on success, 0 on failure
*/
function get_attachment_id( $url ) {
$attachment_id = 0;
$dir = wp_upload_dir();
if ( false !== strpos( $url, $dir['baseurl'] . '/' ) ) { // Is URL in uploads directory?
$file = basename( $url );
$query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
'key' => '_wp_attachment_metadata',
),
)
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) {
foreach ( $query->posts as $post_id ) {
$meta = wp_get_attachment_metadata( $post_id );
$original_file = basename( $meta['file'] );
$cropped_image_files = wp_list_pluck( $meta['sizes'], 'file' );
if ( $original_file === $file || in_array( $file, $cropped_image_files ) ) {
$attachment_id = $post_id;
break;
}
}
}
}
return $attachment_id;
}
이 솔루션의 또 다른 장점은 델이 델의WP_Query
DB에 직접 SQL 쿼리를 작성하는 대신 클래스를 사용합니다.
크기 조정된 이미지, PDF 등의 ID 검색
GFargo가 지적한 것처럼 대부분의 답변은 첨부파일을 이미지라고 가정합니다.또한 attachment_url_to_postid는 (파일 경로가 아닌) URL을 가정합니다.
파일(경로 포함)을 제공하면 실제 질문에 더 잘 대답할 수 있습니다.
function getAttachmentIDFromFile($filepath)
{
$file = basename($filepath);
$query_args = array(
'post_status' => 'any',
'post_type' => 'attachment',
'fields' => 'ids',
'meta_query' => array(
array(
'value' => $file,
'compare' => 'LIKE',
),
)
);
$query = new WP_Query($query_args);
if ($query->have_posts()) {
return $query->posts[0]; //assume the first is correct; or process further if you need
}
return 0;
}
@FrancescoCarlucci의 답변에 따라 개선할 수 있었습니다.
WordPress에서 되어 복사 메타되는 경우가 있습니다._wp_attached_file
이는 답변에 의해 존중되지 않습니다.
여기에서는 다음과 같은 편집이 포함된 상세 쿼리를 보여 줍니다.
function jfw_get_image_id($file_url) {
$file_path = ltrim(str_replace(wp_upload_dir()['baseurl'], '', $file_url), '/');
global $wpdb;
$statement = $wpdb->prepare("SELECT `ID` FROM `wp_posts` AS posts JOIN `wp_postmeta` AS meta on meta.`post_id`=posts.`ID` WHERE posts.`guid`='%s' OR (meta.`meta_key`='_wp_attached_file' AND meta.`meta_value` LIKE '%%%s');",
$file_url,
$file_path);
$attachment = $wpdb->get_col($statement);
if (count($attachment) < 1) {
return false;
}
return $attachment[0];
}
언급URL : https://stackoverflow.com/questions/25671108/get-attachment-id-by-file-path-in-wordpress
'programing' 카테고리의 다른 글
TSQL에서 PRINT 버퍼를 플러시하는 방법 (0) | 2023.04.07 |
---|---|
GETDA를 사용하여 스토어드 프로시저를 호출하는 '' 근처의 구문이 잘못되었습니다.TE (0) | 2023.04.07 |
리액트 라우터 프라이빗루트/리다이렉트가 기능하지 않음 (0) | 2023.03.18 |
콜백에 추가 파라미터 전달 (0) | 2023.03.18 |
데이터 소스 없이 스프링 부트 응용 프로그램 (0) | 2023.03.18 |