如果您有附件的ID,则可以直接获取附件的元数据。附件的alt数据存储在_wp_attachment_image_alt
.
因此,您可以使用:
$alt = get_post_meta( $attachment->ID, \'_wp_attachment_image_alt\', true);
要获取图像的标题,可以使用
wp_get_attachment_metadata()
.
$metadata = wp_get_attachment_metadata( $id );
$caption = $metadata[\'image_meta\'][\'caption\'];
编辑根据您评论中的代码,这是完整的短代码:
function simplisto_the_image($atts) {
$atts = shortcode_atts(
array(
\'to\' => \'http://example.com/image.jpg\'
),
$atts
);
$caption = \'\';
// Get the attachment\'s ID from its URL, if the URL is valid
$url = filter_var( $atts[\'to\'], FILTER_SANITIZE_URL);
if( filter_var( $url, FILTER_VALIDATE_URL) ) {
$attachment_id = attachment_url_to_postid( $url );
// Get the attachment\'s alt, if its a valid ID
if( $attachment_id ){
$caption = wp_get_attachment_caption( $attachment_id );
}
}
$output = \'<div class="lazyimg">\';
$output .= \'<img class="lazyimg-popup" src="\'.$atts[\'to\'].\'" alt="\' .$caption. \'" width="100%" height="auto">\';
$output .= \'<i class="fa fa-expand" aria-hidden="true"></i>\';
$output .= \'</div>\';
return $output;
}
add_shortcode(\'simage\', \'simplisto_the_image\');
短代码将接受图像URL并获取其元数据(如果有效)。