如何在wordpress中检索并显示图像的替代文字?试图替换alt的标题。这是原始代码。
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<h1 class="entry-title"><?php the_title(); ?></h1>
所以在h1我想:
<h1 class="entry-title">"alt text of image"</h1>
尝试将它放在一个变量中:
$alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true);
<h1 class="entry-title"><?php echo $alt_text; ?></h1>
但它没有显示出来。任何解决方案
首先,你需要获得attachment ID
获取alt
文本..
使用此代码来获取,
$img_id = get_post_thumbnail_id(get_the_ID());
现在添加你的代码,
<?php $alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true); ?>
<h1 class="entry-title"><?php echo $alt_text; ?></h1>
确保,你的attachment Alternative Text
不是空的......
你可以从Alternative Text
添加wp-admin --> Media --> edit your attachment --> Alternative Text
......
你可以试试下面的代码:
<?php
$thumb_id = get_post_thumbnail_id(get_the_ID());
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
if( $alt ):
echo $alt;
endif;
?>
我找到了一个脚本,试试这个是否适合你。在主题的functions.php文件中添加它
function isa_add_img_title($ attr,$ attachment = null){
$img_title = trim( strip_tags( $attachment->post_title ) );
$attr['title'] = $img_title;
$attr['alt'] = $img_title;
return $attr;
} add_filter('wp_get_attachment_image_attributes','isa_add_img_title',10,2);
我发现这个剧本在我的最后工作,类似于Mukesh Panchal。我尝试过其他的脚本,但它没有用。
<?php $thumb_id = get_post_thumbnail_id(get_the_ID());
$alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true); ?>
<img class="image" src="<?php echo $feature_image; ?>" alt="<?php echo $alt; ?>" >