如果我理解正确的话,您正在尝试将自定义rel属性和基于附件标题的title属性添加到帖子库中嵌入的每个图像中。您可以尝试使用\'wp_get_attachment_link\'
滤器
<?php
function wpse221533_add_caption_title_to_content_gallery_image_attachments( $markup, $id, $size, $permalink, $icon, $text ) {
//Target only images
if ( ! wp_attachment_is_image( $id ) ) :
return $markup;
endif;
//Limit the scope of the new attributes
$post_types = array( \'post\', \'page\' );
if ( ! is_singular( $post_types ) ) :
return $markup;
endif;
//Get attachment data
$current_attachment_object = get_post( $id );
//Get attachment caption
$current_attachment_caption = $current_attachment_object->post_excerpt;
//Nothing wrong with regex, but str_replace is cheaper
$markup = str_replace( \' href=\', \' rel="lightbox" title="\' . $current_attachment_caption . \'" href=\', $markup );
return $markup;
}
add_filter( \'wp_get_attachment_link\', \'wpse221533_add_caption_title_to_content_gallery_image_attachments\', 10, 6 ) ;
?>
EDIT 16/04/06
事实上,我没有正确理解,因为我指的是帖子的图片库和帖子的单幅图片附件。以上代码仅适用于库。
此其他代码将对单个图像附件执行此操作:
<?php
function wpse221533_add_caption_title_to_content_single_image_attachments( $content ) {
//Limit the scope of the new attributes
$post_types = array( \'post\', \'page\' );
if ( ! is_singular( $post_types ) ) :
return $content;
endif;
//Parse the content DOM for links
$doc = new DOMDocument();
$doc->loadHTML( $content );
$anchors = $doc->getElementsByTagName( \'a\' );
//Parse each link
foreach ( $anchors as $anchor ) :
//Get the rel attribute
$anchor_rel = $anchor->getAttribute( \'rel\' );
//Get the image ID based on the rel attribute
$current_attachment_id = substr( strrchr( $anchor_rel, "-" ), 1 );
//Check if the extracted ID is actually a number
if ( ! is_numeric( $current_attachment_id ) ) :
return $content;
endif;
//Target only images
if ( ! wp_attachment_is_image( $current_attachment_id ) ) :
return $content;
endif;
//Get the attachment object
$current_attachment_object = get_post( $current_attachment_id );
//Get the attachment caption
$current_attachment_caption = $current_attachment_object->post_excerpt;
//Set the rel attribute
$anchor->setAttribute( \'rel\', \'lightbox\' );
//Finally set the title attribute based on the attachment caption
$anchor->setAttribute( \'title\', $current_attachment_caption );
endforeach;
//Save the DOM changes
$content = $doc->saveHTML();
return $content;
}
add_filter( \'the_content\', \'wpse221533_add_caption_title_to_content_single_image_attachments\', 10, 1 );
?>