ACF если оператор не работает, когда поле пустое - PullRequest
0 голосов
/ 18 января 2020

У меня есть поле ACF для изображений героев, которое называется hero_image. Это поле находится в верхней части моей 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, чтобы получить поле извне l oop. Изображение загружается, как и ожидалось.

Если изображение не было загружено для публикации с использованием поля, я ожидаю, что на входе отсутствует разметка. Тем не менее, я все еще вижу следующее:

<div class="hero"></div>

Почему мой оператор if не работает, когда поле не используется?

1 Ответ

0 голосов
/ 20 января 2020

Я продолжил копать и нашел свою проблему.

У меня есть два поля ACF hero_image и thumbnail_image. Они настроены для отображения на всех страницах и в сообщениях, включая пользовательские типы сообщений.

Глядя на файл header.php, я обнаружил вот что:

<?php
    // Get post ID
    $post_id = get_queried_object_id();
    // Hero image
    $hero = get_field('hero_image', $post_id);
    $hero_url = wp_get_attachment_url( get_field('hero_image', $post_id), 'hero');
?>

<?php if ( is_single() || is_archive() ): ?>
    <header id="masthead" class="site-header">
<?php else: ?>
    <header id="masthead" <?php if ($hero) { echo 'class="site-header has-background" style="background:url('.$hero_url.')"'; } else { echo 'class="site-header"'; } ?>>
<?php endif; ?>

Как видите, я ' также используя переменную $post_id вне l oop. Это предотвратило работу второй переменной $post_id через single.php.

Я переименовал $post_id в заголовке. php в $post_id_outside_loop. Затем я использовал эту переменную через single.php, поскольку она также находится за пределами l oop. Это решило проблему.

<?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_outside_loop is set via header.php
    $image = get_field('hero_image', $post_id_outside_loop);
    if ($image) {
        echo '<div class="hero">'.wp_get_attachment_image( $post_id_outside_loop, '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();

            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;

        endwhile; // End of the loop.
        ?>

        </main><!-- #main -->

    </div><!-- #primary -->

    <?php
        get_sidebar();
        get_footer();
    ?>

</div><!-- .has-sidebar -->
...