Created
June 5, 2020 12:15
-
-
Save joeyblake/8a9b09b14bbf5fe7bde6ec720ca607b8 to your computer and use it in GitHub Desktop.
Filter for correcting carbonfields file field type metadata lookup
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 | |
add_filter( 'carbon_fields_attachment_id_from_url' , __NAMESPACE__ . '\get_attachment_id_from_url', 10, 2 ); | |
function get_attachment_id_from_url( $attachment_id, $url ) { | |
if ( 0 === $attachment_id ) { | |
$dir = wp_upload_dir(); | |
$filename = basename( $url ); | |
$filename = str_replace( [ '.doc', '.pdf', '.xls' ], [ '-doc', '-pdf', '-xls' ], $filename ); | |
$filename .= '.jpg'; | |
if ( strpos( $url, $dir['baseurl'] . '/' ) !== false ) { | |
$query_args = array( | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'fields' => 'ids', | |
'meta_query' => array( | |
array( | |
'value' => $filename, | |
'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 === $filename || in_array( $filename, $cropped_image_files ) ) { | |
$attachment_id = intval( $post_id ); | |
break; | |
} | |
} | |
} | |
} | |
} | |
return $attachment_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment