Skip to content

Instantly share code, notes, and snippets.

@joeyblake
Created June 5, 2020 12:15
Show Gist options
  • Save joeyblake/8a9b09b14bbf5fe7bde6ec720ca607b8 to your computer and use it in GitHub Desktop.
Save joeyblake/8a9b09b14bbf5fe7bde6ec720ca607b8 to your computer and use it in GitHub Desktop.
Filter for correcting carbonfields file field type metadata lookup
<?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