注意:Modern Tribe为活动日历创建快捷代码时未定义的变量


Notice: Undefined variable when creating shortcode for The Events Calendar by Modern Tribe

我找到了一个教程,它允许我为"The Events Calendar by Modern Tribe"创建一个快捷代码,允许我显示最近的事件列表。代码正常工作并正确显示列表,但我收到一条通知,上面写着"注意:第40行mysite/themes/theme-name/recent_events.php中的未定义变量:no_upcoming_events"

这是它所指的行:

if ( $posts && !$no_upcoming_events) {

这是完整的代码:

function ckhp_get_tribe_events($atts) {
    if ( !function_exists( 'tribe_get_events' ) ) { 
        return;
    }
    global $wp_query, $tribe_ecp, $post;
    $output='';
    $ckhp_event_tax = '';
    extract( shortcode_atts( array( 
        'cat' => '', 
        'number' => 5,
        'error' => 'y' 
    ), $atts, 'ckhp-tribe-events' ), EXTR_PREFIX_ALL, 'ckhp' );
    if ( $ckhp_cat ) {
        $ckhp_event_tax = array( 
            array(
                'taxonomy' => 'tribe_events_cat',
                'field' => 'slug',
                'terms' => $ckhp_cat
            ) 
        );
    }
    $posts = tribe_get_events(apply_filters('tribe_events_list_widget_query_args', array(
            'eventDisplay' => 'upcoming',
            'posts_per_page' => $ckhp_number,
            'tax_query'=> $ckhp_event_tax
    )));
    if ( $posts && !$no_upcoming_events) {
        $output .= '<ul class="hfeed vcalendar ckhp-small ckhp-event-list">';
        foreach( $posts as $post ) :
            setup_postdata( $post );
            $output .= '<li class="">';
            $output .= '<h4 class="entry-title summary">' . '<a href="' . tribe_get_event_link() . '" rel="bookmark">' . get_the_title() . '</a>' . '</h4>';
            $output .= '<div class="duration venue">' . tribe_events_event_schedule_details() . ' ' . tribe_get_venue() . '</div>';
            $output .= '</li>';
        endforeach;
        $output .= '</ul><!-- .hfeed -->';
        $output .= '<p class="tribe-events-widget-link"><a href="' . tribe_get_events_link() . '" rel="bookmark">' . translate( 'View All Events', 'tribe-events-calendar' ) . '</a></p>';
    } else { //No Events were Found
        $output .= ( $ckhp_error == 'y' ? '<p>' . translate( 'There are no upcoming events at this time.', 'tribe-events-calendar' ) . '</p>' : '' ) ;
    } // endif
    wp_reset_query();
    return $output;
}
add_shortcode('ckhp-tribe-events', 'ckhp_get_tribe_events'); // link new function to shortcode name

我对php不是很熟练,所以我不确定我需要做什么来删除这个通知。如有任何帮助,我们将不胜感激。

PHP不需要显式声明/初始化变量(这有时很方便),但可能会导致这样的问题。

最优雅的解决方案是简单地检查变量是否设置为某个值,然后再测试该值是什么

if ( $posts && isset($no_upcoming_events) && !$no_upcoming_events ) {
    ...
}

如果未设置$no_upcoming_events,则isset将失败,if语句将退出(短路),并且从不检查$no_upcoming_events的值,从而避免错误。