Created
May 10, 2017 21:15
-
-
Save bcole808/7c2f035b64da2f1b1443324f2cdc5908 to your computer and use it in GitHub Desktop.
Get WordPress attachment from post
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 | |
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