今天,我使用regex创建了下面的函数,如果插入到内容中的图像的ALT属性为空,该函数将插入文章标题。
但现在我想要的是图片的标题,而不是帖子的标题。如何制作?
if( ! ( function_exists( \'add_alt_image_content\' ) ) ) {
function add_alt_image_content( $content ) {
if ( is_single() && in_the_loop() && is_main_query() ) {
global $post;
$image = get_post( $post->ID );
$image_title = $image->post_title;
$pattern = \'~(<img.*? alt=")("[^>]*>)~i\';
$replace = \'$1\'.$image_title.\'$2\';
$content = preg_replace( $pattern, $replace, $content );
return $content;
}
}
}
add_filter( \'the_content\', \'add_alt_image_content\' );
SO网友:tiago calado
只需更改$post->;ID with get\\u post\\u thumbnail\\u ID(),并且可能我们还可以删除全局$post;
if( ! ( function_exists( \'add_alt_image_content\' ) ) ) {
function add_alt_image_content( $content ) {
if ( is_single() && in_the_loop() && is_main_query() ) {
global $post;
$image = get_post(get_post_thumbnail_id());
$image_title = $image->post_title;
$pattern = \'~(<img.*? alt=")("[^>]*>)~i\';
$replace = \'$1\'.$image_title.\'$2\';
$content = preg_replace( $pattern, $replace, $content );
return $content;
}
}
}
add_filter( \'the_content\', \'add_alt_image_content\' );