简体   繁体   English

获取 Wordpress 特色图片“alt”

[英]Get Wordpress Featured Image “alt”

I'm trying to get a page's featured image alt and echo it as paragraph text but my code doesn't seem to be working.我正在尝试获取页面的特色图像 alt 并将其作为段落文本回显,但我的代码似乎不起作用。

I'm currently able to echo the image and it's working perfectly.我目前能够回显图像并且它运行良好。

Here's the code I'm using:这是我正在使用的代码:

    <?php
    get_header(); ?>
      </div>
    <?php /* The loop */ ?>
    <?php while ( have_posts() ) : the_post(); ?>
    <div class="header-image">

    <?php echo get_the_post_thumbnail($page->ID, 'full'); ?> 
    
    <?php $alt = get_post_meta( $attachment_img->ID, '_wp_attachment_image_alt', true ); ?>
    
    <p><?php echo $alt; ?></p>
    
    </div>

Check if you get correct thumbnail id.检查您是否获得正确的缩略图 ID。
For me this code works perfect:对我来说,这段代码很完美:

$thumbnail_id = get_post_thumbnail_id( $post->ID );
$alt = get_post_meta($thumbnail_id, '_wp_attachment_image_alt', true);

Here's a solution :这是一个解决方案

  $thumbnail_id    = get_post_thumbnail_id($post->ID);
  $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

  if ($thumbnail_image && isset($thumbnail_image[0])) {
    echo '<span>'.$thumbnail_image[0]->post_excerpt.'</span>';
  }

Or you can use your code, but instead of echoing $alt directly you need to echo $alt->post_excerpt .或者您可以使用您的代码,但不是直接回显$alt ,您需要回显$alt->post_excerpt

If you want to get the alt text of your featured image, you can get it with this code...如果您想获取特色图片的替代文字,可以使用此代码获取...

<?php echo get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true); ?>

So if you want to place it in a P tag, this will work...所以如果你想把它放在一个 P 标签中,这将起作用......

<p><?php echo get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true); ?></p>

Hope it helps you, or someone at least.希望它可以帮助您,或者至少对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM