【问题标题】:How can I dynamically call an <img> alt attribute?如何动态调用 <img> alt 属性?
【发布时间】:2018-03-24 16:59:56
【问题描述】:

我正在开发一个 WordPress 网站,我已将以下代码插入到 header.php 文件中,以便动态调用自定义徽标:

<?php
if ( function_exists( 'has_custom_logo' ) ) {
    has_custom_logo();
} 
?>

虽然这有效,但我在调整尺寸大小时遇到​​了问题。因此,我将代码替换为以下代码:

<?php 
    $custom_logo_id = get_theme_mod( 'custom_logo' );
    $logo = wp_get_attachment_image_src( $custom_logo_id , 'thumbnail' ); 
        if ( has_custom_logo() ) {
            echo '<img src="'. esc_url( $logo[0] ) .'">';
        } 
        else {
            echo '<h1>'. get_bloginfo( 'name' ) .'</h1>'; 
        }
?>

此替代代码也称为自定义徽标,并允许我通过 wp_get_attachment_image_src() 参数更改自定义徽标尺寸。

不利的一面是它剥离了其Alt 属性的HTML img 输出。

有没有办法动态调用Alt 属性?我想我需要将它附加到 echo '&lt;img src="'. esc_url( $logo[0] ) .'"&gt;'; 条目。

最新代码:

<?php
$custom_logo_id = get_theme_mod( 'custom_logo' );    
$custom_logo_attr = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );


    if ( has_custom_logo() ) {
        echo wp_get_attachment_image($custom_logo_id, 'thumbnail', false, $custom_logo_attr);
    } 

    else {
        echo '<h1>'. get_bloginfo( 'name' ) .'</h1>'; 
    }               
?>

【问题讨论】:

    标签: php html wordpress


    【解决方案1】:

    根据get_custom_logo()的参考,可以通过get_post_meta()获取logo图片alt数据。

    /*
     * If the logo alt attribute is empty, get the site title and explicitly
     * pass it to the attributes used by wp_get_attachment_image().
     */
    $image_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
    if ( empty( $image_alt ) ) {
      $custom_logo_attr['alt'] = get_bloginfo( 'name', 'display' );
    }
    
    /*
     * If the alt attribute is not empty, there's no need to explicitly pass
     * it because wp_get_attachment_image() already adds the alt attribute.
     */
    $html = sprintf( '<a href="%1$s" class="custom-logo-link" rel="home" itemprop="url">%2$s</a>',
      esc_url( home_url( '/' ) ),
      wp_get_attachment_image( $custom_logo_id, 'full', false, $custom_logo_attr )
    );
    

    wp_get_attachment_image() 函数接受 $attr parameter

    wp_get_attachment_image( int $attachment_id, string|array $size = 'thumbnail',  
                             bool $icon = false, string|array $attr = '' )  
    

    $attr (字符串|数组)(可选)图像标记的属性。 默认值:''

    【讨论】:

    • 不确定我是否做错了,但是当我输入您建议的代码时,图像不再显示。
    • 嗯,你有什么错误吗?你还在输出$logo吗?如果可能,请edit your question 并在原始帖子后添加更新后的代码。
    • 我刚刚检查了源代码,除了我放置代码的空&lt;div&gt; 容器外,没有任何内容与您的建议代码一​​起输出。
    • 你如何回显生成的 HTML(上例中的$html)?
    • 我已插入:echo '&lt;img src="'. esc_url( $html ) .'"&gt;'; 我认为此代码有错误?
    【解决方案2】:

    在 php 中创建一个子文件夹,将您的图像拖放到该文件夹​​中,然后只需拖放链接,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      相关资源
      最近更新 更多