I have an ACF field for hero images called hero_image. This field sits at the top of my single.php page like so:
<?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 -->
I'm using the $post_id variable to fetch the field from outside the loop. The image loads as expected.
If an image hasn't been uploaded for a post using the field, I'm expecting there to be no markup on the front-end. However, I still see the following:
Why isn't my if statement working when the field isn't in use?
Aucun commentaire:
Enregistrer un commentaire