phpwordpressfunctionisset

Why do I get undefined index error on my PHP function code


I even tried using "isset", but sadly it is not working.

function pageBanner($args=NULL){
if(!$args['title']){
    $args['title']=get_the_title();
}

if (!$args['subtitle']){
    $args['subtitle'] = get_field('page_banner_subtitle');
}

if (!$args['photo']){
    if (get_field('page_banner_background_image')){
        $args['photo'] = get_field('page_banner_background_image')['sizes']['pageBanner'];
    }
    else {
        $args['photo']=get_theme_file_uri('images/pages.jpg');
    }
}?>

I didn't know the problem on my if(!$args['title']){ $args['title']=get_the_title(); it is working, but the subtitle and photo are undefined index.


Solution

  • Try something like this:

    function pageBanner($args = null)
    {
        if ($args === null) {
            $args = [];
        }
    
        if (!isset($args['title'])) {
            $args['title'] = get_the_title();
        }
    
        if (!isset($args['subtitle'])) {
            $args['subtitle'] = get_field('page_banner_subtitle');
        }
    
        if (!isset($args['photo'])) {
            $field = get_field('page_banner_background_image');
            if ($field && isset($field['sizes']['pageBanner'])) {
                $args['photo'] = $field['sizes']['pageBanner'];
            } else {
                $args['photo'] = get_theme_file_uri('images/pages.jpg');
            }
        }
    }