如果要获取帖子内容中的实际图像,可以使用正则表达式对其进行匹配。
要仅获取图像URL和维度,您的代码可以如下所示:
if( is_single() ) {
global $post;
// Match the image URLs inside the post content
$pattern = \'/<img.*src="([^"]+)"[^>]*>/\';
$matches = [];
preg_match_all( $pattern, $post->post_content, $matches );
// Start looping if there are matches
foreach ( $matches[1] as $url ) {
// Remove the size portion from image URL to get the full size URL
$url = preg_replace( \'/(\\-[0-9]+x[0-9]+)(.*)$/i\', "$2", $url );
// calculate the image dimensions
$image_dimensions = getimagesize($url);
// Do whatever you want here...
}
}
但是,如果需要获取附件的WP\\u Post对象,则必须使用
attachment_url_to_postid 然后从中获取WP\\u Post;您的代码可能如下所示:
if( is_single() ) {
global $post;
// Match the image URLs inside the post content
$pattern = \'/<img.*src="([^"]+)"[^>]*>/\';
$matches = [];
preg_match_all( $pattern, $post->post_content, $matches );
// Start looping if there are matches
foreach ( $matches[1] as $url ) {
// Remove the size portion from image URL to get the full size URL
$url = preg_replace( \'/(\\-[0-9]+x[0-9]+)(.*)$/i\', "$2", $url );
// Convert the image URL to the corresponding post ID
$attachment_id = attachment_url_to_postid( $url );
// Get the WP_Post object for the attachment
$attachment = get_post( $attachment_id );
// Do whatever you want here...
}
}
获取插入图像的post ID的另一种方法是匹配图像的HTML类。WordPress广告a类;wp image-{attachmentid}”字样;通过编辑器向每个插入的图像发送,其中{attachmentid}是插入图像的post ID。
因此,您的代码可能是这样的:
if( is_single() ) {
global $post;
// Match the attachments IDs inside the post content
$pattern = \'/<img.+wp\\-image\\-([0-9]+)[^>]+>/\';
$matches = [];
preg_match_all( $pattern, $post->post_content, $matches );
// Start looping in the found matches
foreach ( $matches[1] as $attachment_id ) {
// Get the WP_Post object for the attachment
$attachment = get_post( $attachment_id );
// Do whatever you want here...
}
}