Custom Fields for Div background images? (wordpres

2019-06-01 20:18发布

I'm wondering how this would be done, I've seen an example on smashingmagazine but that is for the post background in the index feed and requires a plug in,I assumed it would simply be a case of

<div background="<?php the_field('custom_field_name');?>">

this however, hasn't worked so far, I'm guessing this is due to me not setting a specific direct url, however since I'm able to place images via custom field in the post I'm sure its possible to get the effect I want achieved.

Another idea I had was to set an with the source as a custom field via php, which I have already done for my custom theme, though I'm not sure about the correct css to applied to the img class and it's container div to make sure it functions as the background.

2条回答
We Are One
2楼-- · 2019-06-01 20:38

What you need is:

Adds a custom field (also called meta-data) to a specified post which could be of any post type. A custom field is effectively a key–value pair.

Note that if the given key already exists among custom fields of the specified post, another custom field with the same key is added unless the $unique argument is set to true, in which case, no changes are made. If you want to update the value of an existing key, use the update_post_meta() function instead.

More Here on Wordpress codex: http://codex.wordpress.org/Function_Reference/add_post_meta

查看更多
神经病院院长
3楼-- · 2019-06-01 20:39

There is no background attribute in HTML. What you want instead is an inline CSS property with the style. So your desired result is:

<div style="background-image: url('http://absolute/path/to/img.jpg');">

And the code to get there depends on what is stored in your custom_field_name custom field. If it's an absolute url, then all you need is

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

If it's a relative URL to eg. the theme root, add get_stylesheet_directory_uri(); in front of the_field(). I'd avoid hardcoding the first part of the absolute URL, but it's possible if you don't need the solution to be portable.

查看更多
登录 后发表回答