如何获取自定义页眉图像的alt文本?

时间:2014-06-26 作者:henrywright

我用的是custom header 在我的主题中。我的目标是添加alt 自定义标题的属性img 要素我的img 到目前为止,元素如下所示:

<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />
如何获取自定义标题图像的alt文本?

2 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成
/**
 * Get custom header\'s alt data.
 * 
 * @link    http://wordpress.stackexchange.com/q/151850/1685
 * 
 * @return  string
 */
function wpse_151850_get_header_image_alt() {
    $attachment_id = 0;

    if ( is_random_header_image() && $header_url = get_header_image() ) {
        // For a random header, we have to search for a match against all headers.
        foreach ( get_uploaded_header_images() as $header ) {
            if ( $header[\'url\'] == $header_url ) {
                $attachment_id = $header[\'attachment_id\'];
                break;
            }
        }

    } elseif ( $data = get_custom_header() ) {
        // For static headers, less intensive approach.
        $attachment_id = $data->attachment_id;
    } 

    if ( $attachment_id ) {
        $alt = trim( strip_tags( get_post_meta( $attachment_id, \'_wp_attachment_image_alt\', true ) ) );

        if ( ! $alt ) // Fallback to caption (excerpt)
            $alt = trim( strip_tags( get_post_field( \'post_excerpt\', $attachment_id ) ) );
        if ( ! $alt ) // Fallback to title
            $alt = trim( strip_tags( get_post_field( \'post_title\', $attachment_id ) ) );
    } else {
        $alt = \'\';
    }

    return $alt;
}
SO网友:DevTurtle

好吧,我找到了答案,我已经在网上找了好几天了。

下面是我如何做到这一点的。希望这对其他人有帮助

// This is getting the image / url
$feature1 = get_theme_mod(\'feature_image_1\');

// This is getting the post id
$feature1_id = attachment_url_to_postid($feature1);

// This is getting the alt text from the image that is set in the media area
$image1_alt = get_post_meta( $feature1_id, \'_wp_attachment_image_alt\', true );
标记

<a href="<?php echo $feature1_url; ?>"><img class="img-responsive center-block" src="<?php echo $feature1; ?>" alt="<?php echo $image1_alt; ?>"></a>

结束

相关推荐

将php函数添加到.js文件中(用于tinyMCE按钮)

我正在为wp WYSIWYG编辑器创建一个tinyMCE按钮。基本上,当用户单击按钮时,会弹出一个模式表单,他们必须输入几个字段。但是,其中一个字段需要是列出每个帖子类别的列表框,用户将选择一个。其基本语法如下:{ type: \'listbox\', name: \'sds-category\', label: \'Category\', \'values\': [ {text: \'Name Of Cat\', value: \'Cat ID\'}