Use regex to find all the urls and filter by type.
$post = get_post( 504 );
$content = $post->post_content;
// match all urls
preg_match_all( '/(http:|https:)?\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/', $content, $matches );
$count = 0;
if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) {
foreach ( $matches[ 0 ] as $url ) {
$split = explode( '#', $url );
$split = explode( '?', $split[ 0 ] );
$split = explode( '&', $split[ 0 ] );
$filename = basename( $split[ 0 ] );
$file_type = wp_check_filetype( $filename, wp_get_mime_types() );
if ( ! empty ( $file_type[ 'ext' ] ) ) {
// (optional) limit inclusion based on file type
if( ! in_array( $file_type[ 'ext' ], array('jpg', 'png')) ) continue;
$files[ $url ] = $file_type;
$urls[]=$url;
$count ++;
}
}
}
// print out urls and total count
print_r( array (
'total' => $count,
'unique' => array_keys( $files ),
'urls' => $urls
) );
OOP
If you want this as a reusable function…
function get_file_urls( $content="", $file_types = array ( 'jpg', 'png' ) ) {
// match all urls
preg_match_all( '/(http:|https:)?\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/', $content, $matches );
$urls = array ();
$files = array ();
if ( ! empty( $matches ) && ! empty( $matches[ 0 ] ) ) {
foreach ( $matches[ 0 ] as $url ) {
$split = explode( '#', $url );
$split = explode( '?', $split[ 0 ] );
$split = explode( '&', $split[ 0 ] );
$filename = basename( $split[ 0 ] );
$file_type = wp_check_filetype( $filename, wp_get_mime_types() );
if ( ! empty ( $file_type[ 'ext' ] ) ) {
// (optional) limit inclusion based on file type
if ( ! in_array( $file_type[ 'ext' ], $file_types ) ) {
continue;
}
$files[ $url ] = $file_type;
$urls[] = $url;
}
}
}
// print out urls and total count
return array (
'total' => count( $urls ),
'urls' => $urls,
'total_unique' => count( $files ),
'unique' => array_keys( $files ),
);
}
$post = get_post( 504 );
$content = $post->post_content;
$file_urls = get_file_urls( $content, array ( 'jpg' ) );
$count = $file_urls[ 'total' ];
echo "<div class="count">${count}</div>";