简体   繁体   English

在 wordpress 中制作动态背景图像

[英]making a background image dynamic in wordpress

I am trying to get my background image dynamic in wordpress.我正在尝试在 wordpress 中动态获取我的背景图像。 My goal is to have the user to be able to change the background image through wordpress dashboard.我的目标是让用户能够通过 wordpress 仪表板更改背景图像。 I am using Advanced Custom Field plugin.我正在使用高级自定义字段插件。

I've read through Advanced Custom Field website but couldn't find anything on background images on it.我已经阅读了 Advanced Custom Field 网站,但在其背景图片上找不到任何内容。

Sample code will be helpful.示例代码会有所帮助。

Thank you谢谢

ACF does not provide separate field for the background image but you can use the simple image filed and use it to set your background image. ACF 不为背景图像提供单独的字段,但您可以使用简单的图像字段并使用它来设置背景图像。

for that define an image field from ACF menu.为此,从 ACF 菜单定义一个图像字段。 and paste this code in your page where you want to put the background image并将此代码粘贴到您要放置背景图像的页面中

<div style="background-image: url(<?php echo get_field('background'); ?>);"><div>

as you can see you can use css property background-image to set the background image here it will fetch the image stored in 'background' field and put it as an background image.如您所见,您可以使用 css 属性background-image在这里设置背景图像,它将获取存储在“背景”字段中的图像并将其作为背景图像。

PS:- you have to replace fieldname 'background' with your field name. PS:-您必须用您的字段名称替换字段名称“背景”。

you can output dynamic styles in the header of your page by using the wp_head hook.您可以使用 wp_head 挂钩在页面标题中输出动态样式。 here is an example (add this in your functions.php):这是一个例子(在你的functions.php中添加这个):

function my_inline_styles() {
    $body_bg_image="/wp-content/uploads/myimg.jpg"; //here you would get your value from ACF
    ?>
<!-- start my dynamic styles-->
<style type="text/css">
    body {background-image: url('<?= $body_bg_image ?>')};
</style>
<!-- end my dynamic styles-->
    <?php
}
add_action('wp_head', 'my_inline_styles');

i would recommend sticking them into the header instead of the footer, to ensure early loading of these styles.我建议将它们粘贴到页眉而不是页脚中,以确保尽早加载这些样式。

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

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