Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bcole808/7c2f035b64da2f1b1443324f2cdc5908 to your computer and use it in GitHub Desktop.
Save bcole808/7c2f035b64da2f1b1443324f2cdc5908 to your computer and use it in GitHub Desktop.
Get WordPress attachment from post
<?php
function get_random_attachment_id_from_post($post = 0) {
$post = get_post( $post );
if ( ! preg_match_all( '/<img [^>]+>/', $post->post_content, $matches ) ) {
return 0;
}
$attachment_ids = array();
foreach( $matches[0] as $image ) {
if ( preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) && ( $attachment_id = absint( $class_id[1] ) ) ) {
$attachment_ids[] = $attachment_id;
}
}
if ($attachment_ids) {
return $attachment_ids[0];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment