简体   繁体   English

在 Timber/Twig 主题中使用 WordPress 自定义 header 图像

[英]Use WordPress custom header image in Timber/Twig theme

WordPress/Timber/Twig theme newbie here. WordPress/Timber/Twig 主题新手在这里。 I am wanting to bring the theme custom header image into a Timber-based Twig theme.我想将主题自定义 header 图像带入基于木材的 Twig 主题。 I know you need to tie into the theme customizer API and have this code {{ function('get_theme_mod', 'name') }} , but I do not know how to adapt it to work with custom header images.我知道您需要绑定到主题定制器 API 并拥有此代码{{ function('get_theme_mod', 'name') }} ,但我不知道如何使其适用于自定义 header 图像。

Any suggestions or tips?有什么建议或提示吗?

I have figured out the function code.我已经弄清楚了 function 代码。 I have accessed the image source using {{ function('get_theme_mod', 'header_image') }} , but now I am wondering how to access the alt text defined for the custom header image using Timber/Twig.我已经使用{{ function('get_theme_mod', 'header_image') }}访问了图像源,但现在我想知道如何使用 Timber/Twig 访问为自定义 header 图像定义的 alt 文本。

You can get the image from customizer using below:您可以使用以下方法从定制器获取图像:

{{ theme.theme_mod('header_image')

If you want to get the alt attribute then you can create a filter that can get you the the alt attribute of an image URL.如果要获取alt属性,则可以创建一个过滤器,该过滤器可以获取图像 URL 的 alt 属性。

First, create a function in functions.php:首先,在functions.php中创建一个function:

public function altText( $url ) {
    $feature1_id = attachment_url_to_postid( $url );
    $image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );

    return $image1_alt;
}

Then add it as a filter:然后将其添加为过滤器:

$twig->addFilter( new Twig\TwigFilter( 'altText', array( $this, 'altText' ) ) );

Then use it in the template:然后在模板中使用它:

{{ theme.theme_mod('header_image') | altText }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM