首页 > 解决方案 > 随机 WordPress 未定义变量

问题描述

我最近突然遇到了一个 WordPress 网站的未定义变量。我看到它是用 if 语句定义的(我认为这是无效的)。我在哪里可以放置它以消除错误。该站点呈现正常,但显示错误消息。消息是“注意:未定义的变量:第 29 行 /nas/content/live/qsrautomations/wp-content/themes/qsrautomations/lib/page-header.php 中的 background_image”

function qsrautomations_opening_page_header() {
if ( ( is_front_page() && is_active_sidebar( 'front-page-hero' ) ) || ( is_page() && !is_page_template( 'page_landing.php' ) ) || is_single() || is_archive() || is_home() ) {

    if ( is_front_page() && is_active_sidebar( 'front-page-hero' ) ) {
        $hero_image = get_option( 'qsrautomations-hero-image', sprintf( '%s/images/hero-image-1.jpg', get_stylesheet_directory_uri() ) );
        $background_image = 'style="background-image: url(' . $hero_image . ')"';
    }

    if ( ( is_page() || ( is_home() && get_option('page_for_posts') ) ) && has_post_thumbnail() ) {
        if ( is_home() && get_option('page_for_posts') ) {
            $posts_page_id = get_option('page_for_posts');
            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $posts_page_id ), 'full' );
        } else {
            $image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
        }
        $background_image = 'style="background-image: url(' . $image[0] . ')"';
    }

    if ( $background_image ) {
        $background_image_class = 'with-background-image';
    }

    ?>

    <div class="header-wrap bg-primary <?php echo $background_image_class; ?>" <?php echo $background_image; ?>>

    <?php
}

}

标签: phpwordpress

解决方案


我没有经常使用 wordpress,但您可能需要分配变量 $background_image = ''; 如下所示,希望这对你有用。

<?php

function qsrautomations_opening_page_header() {
if ( ( is_front_page() && is_active_sidebar( 'front-page-hero' ) ) || ( is_page() && !is_page_template( 'page_landing.php' ) ) || is_single() || is_archive() || is_home() ) {

    $background_image = '';
    if ( is_front_page() && is_active_sidebar( 'front-page-hero' ) ) {
        $hero_image = get_option( 'qsrautomations-hero-image', sprintf( '%s/images/hero-image-1.jpg', get_stylesheet_directory_uri() ) );
        $background_image = 'style="background-image: url(' . $hero_image . ')"';
    }

    if ( ( is_page() || ( is_home() && get_option('page_for_posts') ) ) && has_post_thumbnail() ) {
        if ( is_home() && get_option('page_for_posts') ) {
            $posts_page_id = get_option('page_for_posts');
            $image = wp_get_attachment_image_src( get_post_thumbnail_id( $posts_page_id ), 'full' );
        } else {
            $image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
        }
        $background_image = 'style="background-image: url(' . $image[0] . ')"';
    }

    // if ( $background_image ) {
    //     $background_image_class = 'with-background-image';
    // }

    ?>

    <div class="header-wrap bg-primary <?php echo $background_image_class; ?>" <?php echo $background_image; ?>>

    <?php
}

推荐阅读