Aleš Sýkora / March 22, 2022 / 2 comments
Get all post attached images IDs in WordPress
1 min read / Custom Code, WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: If you need to get IDs of all images attached of current post, add this code to your page (you can use the code block if you use Oxygen builder): You can change the return to print_r($ids); if you need to show the values of array on frontend.
If you need to get IDs of all images attached of current post, add this code to your page (you can use the code block if you use Oxygen builder):
<?php
$images = get_attached_media( 'image' );
if ( $images ) {
$ids = array(); // reset incase there are any defined gallery images lets not include them
foreach ( $images as $image ) {
$ids[] = $image->ID;
}
}
return $ids;
?>
You can change the return to print_r($ids); if you need to show the values of array on frontend.
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻
Kevin
This is somehow not working for me. Not returning ID’s that can be used ( forexample ) in the gallery funtion with oxygen
Aleš Sýkora
Look at the official docs: https://developer.wordpress.org/reference/functions/get_attached_media/
And try to print_r the values. I am not sure if this can be used with Oxygen Gallery, but the code works.