【发布时间】:2020-05-05 05:20:36
【问题描述】:
我有一个名为 hero_image 的英雄图像的 ACF 字段。该字段位于我的 single.php 页面的顶部,如下所示:
<?php
/**
* The template for displaying all single posts
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
*
* @package sitename
*/
get_header();
?>
<?php
$post_id = get_the_ID(); // Required as outside the loop
$image = get_field('hero_image', $post_id);
if ($image) {
echo '<div class="hero">'.wp_get_attachment_image( $image, 'hero').'</div>';
}
?>
<div class="has-sidebar">
<div id="primary" class="content-area">
<main id="main" class="site-main">
<?php
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content', get_post_type() );
the_post_navigation();
endwhile; // End of the loop.
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
?>
</div><!-- .has-sidebar -->
我正在使用$post_id 变量从循环外部获取字段。图像按预期加载。
如果尚未使用该字段为帖子上传图片,我希望前端没有标记。但是,我仍然看到以下内容:
<div class="hero"></div>
为什么当字段不使用时我的 if 语句不起作用?
【问题讨论】:
-
您是否检查过 cmets_open() 发送的内容或 get_cmets_number() 发送的内容...??如果其中任何一个为真...您的 if 将起作用...因为您使用了 OR
-
评论已关闭,所以我不应该想象它正在发送任何内容。我已将其注释掉,结果保持不变。
-
试试 if(trim($image)!= Null) 而不是 if($image)
-
如果图片没有上传,$image会发送什么?
-
如果图像尚未上传,
if(trim($image)!= Null)和if($image)仍会输出<div class="hero"></div>。
标签: php if-statement advanced-custom-fields