I reviewed https://toolset.com/documentation/customizing-sites-using-php/functions/#image and didn't see a built-in way to return the Attachment ID instead of the Attachment URL.
Please advise. If not available at this time, please add to your feature requests.
Waqar
Supporter
Languages:
English (English )
Timezone:
Asia/Karachi (GMT+05:00)
Hi Clifford,
Thank you for contacting us and I'd be happy to assist.
Your observation is correct and Types Fields API ( https://toolset.com/documentation/customizing-sites-using-php/functions/#image ), doesn't offer a built-in method to get the attachment ID.
You're welcome to submit this as feature request through our dedicated form:
https://toolset.com/home/contact-us/suggest-a-new-feature-for-toolset/
For now, you can use "attachment_url_to_postid" function from WordPress ( ref: https://developer.wordpress.org/reference/functions/attachment_url_to_postid/ ) in a custom shortcode, to get the attachment ID through Attachment URL.
Example:
function get_image_id_from_url_func( $atts )
{
$a = shortcode_atts( array(
'url' => ''
), $atts );
// get the image's ID from its URL
$image_id = attachment_url_to_postid( $atts['url'] );
if( !empty($image_id) ){
return $image_id;
}
}
add_shortcode( 'get_image_id_from_url', 'get_image_id_from_url_func' );
Note: The above code snippet can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through active theme's "functions.php" file.
After that, you'll be able to use this new shortcode, to get the ID from the image field like this:
[get_image_id_from_url url="[types field='image-field-slug' output='raw'][/types]"]
You'll replace "image-field-slug" with the actual slug of your image field.
I hope this helps and please let me know if you need any further assistance around this.
regards,
Waqar
Thanks for such a helpful response!
I saw attachment_url_to_postid() but thought it was to get the Post the Media File was attached to, not the File's own Post ID. That's what I needed.
As a suggestion, I'd request the Image field to add an 'ID' output attribute, alongside 'raw' and 'normal'