簡體   English   中英

我如何檢索和顯示 wordpress 中圖像的替代文本?

[英]how do i retrieve and display the alt text of an image in wordpress?

我如何檢索和顯示 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 Textwp-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 文件中添加這個

函數 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; ?>" >

下面的代碼解決了這個問題。 當頁面加載時,它會找到所有缺少替代文本的圖像,並查看您是否在媒體庫中為其指定了替代文本。 如果是這樣,它會在加載頁面之前更新圖像。

add_filter( 'render_block', function( $content, $block ) {
    if( 'core/image' !== $block['blockName'] )
        return $content;

    $alt = get_post_meta( $block['attrs']['id'], '_wp_attachment_image_alt', true );
    if( empty( $alt ) )
        return $content;

    // Empty alt
    if( false !== strpos( $content, 'alt=""' ) ) {
        $content = str_replace( 'alt=""', 'alt="' . $alt . '"', $content );

    // No alt
    } elseif( false === strpos( $content, 'alt="' ) ) {
        $content = str_replace( 'src="', 'alt="' . $alt . '" src="', $content );
    }

    return $content;
}, 10, 2 );
<?php $image_id = get_post_thumbnail_id();
$image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
$image_title = get_the_title($image_id);?>
<img alt="<?php echo $image_title;?>">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM