use*_*973 3 php wordpress image alt
如何在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>
Run Code Online (Sandbox Code Playgroud)
所以在 h1 我想要:
<h1 class="entry-title">"alt text of image"</h1>
Run Code Online (Sandbox Code Playgroud)
试着把它放在一个像这样的变量中:
$alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true);
<h1 class="entry-title"><?php echo $alt_text; ?></h1>
Run Code Online (Sandbox Code Playgroud)
但它没有出现。任何解决方案?
首先,您需要attachment ID
获取alt
文本。
使用此代码来获取,
$img_id = get_post_thumbnail_id(get_the_ID());
Run Code Online (Sandbox Code Playgroud)
现在添加您的代码,
<?php $alt_text = get_post_meta($img_id , '_wp_attachment_image_alt', true); ?>
<h1 class="entry-title"><?php echo $alt_text; ?></h1>
Run Code Online (Sandbox Code Playgroud)
确保你attachment Alternative Text
的不是空的......
您可以Alternative Text
从wp-admin --> Media --> edit your attachment --> Alternative Text
...