php 获取 Wordpress 特色图片“alt”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19267650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:09:13  来源:igfitidea点击:

Get Wordpress Featured Image "alt"

phpwordpress

提问by babusi

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>

采纳答案by Dzhuneyt

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 $altdirectly you need to echo $alt->post_excerpt.

或者您可以使用您的代码,但不是$alt直接回显,而是需要 echo $alt->post_excerpt

回答by gregmatys

Check if you get correct thumbnail id.
For me this code works perfect:

检查您是否获得正确的缩略图 ID。
对我来说,这段代码很完美:

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