gpt4 book ai didi

php - 如何动态调用 alt 属性?

转载 作者:行者123 更新时间:2023-11-28 03:54:10 25 4
gpt4 key购买 nike

我在 WordPress 网站上工作,我已将以下代码插入到 header.php 中文件,以便动态调用自定义 Logo :

<?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>';
}
?>

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

缺点是它去除了 HTML imgAlt 的输出属性。

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

最新代码:

<?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>';
}
?>

最佳答案

根据 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 (string|array) (Optional) Attributes for the image markup. Default value: ''

关于php - 如何动态调用 <img> alt 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46714978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com