从 WordPress 高级自定义字段中删除前端依赖项
Removing frontend dependancies from WordPress Advanced Custom Fields
我正在努力使我的主题完全独立于 ACF 的 get_field
和 the_field
(因此即使插件被禁用,网站也不会中断)。我有一个通过自定义字段 'slider_image'
作为内联 background-image
加载的图像。我需要调用图像的URL。是否可以将其加载到内联 html 中?这是工作代码(带 ACF 的 the_field
):
<!-- Hero Image -->
<section class="hero" style="background: url('<?php the_field('slider_image'); ?>') no-repeat center center; background-size: cover;">
</section>
<!-- End Hero Image -->
如果插件被禁用,我如何使用 get_post_meta
重写此语句?
我试过:
<section class="hero" style="background: url('<?php echo get_post_meta( get_the_ID(), 'slider_image', true ); ?>') no-repeat center center; background-size: cover;">
哪个returns:
<section class="hero" style="background: url('98') no-repeat center center; background-size: cover;">
这必须是附加图像 post 的 ID。要获取当前图像,您必须使用一些嵌入式 WP 函数,例如 wp_get_attachment_image (if you want to print image tag) or wp_get_attachment_image_src(如果您需要图像属性)
例如在你的情况下,当你只想要 url
图像时,你可以这样做:
$img_id = get_post_meta( get_the_ID(), 'slider_image', true );
$image_attr = wp_get_attachment_image_src( $img_id, 'large' ); //returns false or array
if ( $image_attr ) {
$img_url = $image_attr[0]; ?>
<section class="hero" style="background: url('<?php echo $img_url; ?>') no-repeat center center; background-size: cover;">
<?php } ?>
我正在努力使我的主题完全独立于 ACF 的 get_field
和 the_field
(因此即使插件被禁用,网站也不会中断)。我有一个通过自定义字段 'slider_image'
作为内联 background-image
加载的图像。我需要调用图像的URL。是否可以将其加载到内联 html 中?这是工作代码(带 ACF 的 the_field
):
<!-- Hero Image -->
<section class="hero" style="background: url('<?php the_field('slider_image'); ?>') no-repeat center center; background-size: cover;">
</section>
<!-- End Hero Image -->
如果插件被禁用,我如何使用 get_post_meta
重写此语句?
我试过:
<section class="hero" style="background: url('<?php echo get_post_meta( get_the_ID(), 'slider_image', true ); ?>') no-repeat center center; background-size: cover;">
哪个returns:
<section class="hero" style="background: url('98') no-repeat center center; background-size: cover;">
这必须是附加图像 post 的 ID。要获取当前图像,您必须使用一些嵌入式 WP 函数,例如 wp_get_attachment_image (if you want to print image tag) or wp_get_attachment_image_src(如果您需要图像属性)
例如在你的情况下,当你只想要 url
图像时,你可以这样做:
$img_id = get_post_meta( get_the_ID(), 'slider_image', true );
$image_attr = wp_get_attachment_image_src( $img_id, 'large' ); //returns false or array
if ( $image_attr ) {
$img_url = $image_attr[0]; ?>
<section class="hero" style="background: url('<?php echo $img_url; ?>') no-repeat center center; background-size: cover;">
<?php } ?>